/
respond.go
82 lines (66 loc) · 2.29 KB
/
respond.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
Copyright 2022 Cortex Labs, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package endpoints
import (
"encoding/json"
"net/http"
"github.com/cortexlabs/cortex/pkg/lib/errors"
libjson "github.com/cortexlabs/cortex/pkg/lib/json"
"github.com/cortexlabs/cortex/pkg/lib/logging"
"github.com/cortexlabs/cortex/pkg/lib/telemetry"
"github.com/cortexlabs/cortex/pkg/operator/schema"
)
var operatorLogger = logging.GetLogger()
func respondJSON(w http.ResponseWriter, r *http.Request, response interface{}) {
jsonBytes, err := libjson.Marshal(response)
if err != nil {
respondError(w, r, errors.Wrap(err, "failed to encode response"))
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(jsonBytes)
}
func respondError(w http.ResponseWriter, r *http.Request, err error, strs ...string) {
respondErrorCode(w, r, http.StatusBadRequest, err, strs...)
}
func respondErrorCode(w http.ResponseWriter, r *http.Request, code int, err error, strs ...string) {
err = errors.Wrap(err, strs...)
if !errors.IsNoTelemetry(err) {
errTags := map[string]string{}
if clientID := r.Context().Value(ctxKeyClient); clientID != nil {
if clientIDStr, ok := clientID.(string); ok {
errTags["client_id"] = clientIDStr
}
}
telemetry.Error(err, errTags)
}
if !errors.IsNoPrint(err) {
operatorLogger.Error(err)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
response := schema.ErrorResponse{
Kind: errors.GetKind(err),
Message: errors.Message(err),
}
json.NewEncoder(w).Encode(response)
}
func recoverAndRespond(w http.ResponseWriter, r *http.Request, strs ...string) {
if errInterface := recover(); errInterface != nil {
err := errors.CastRecoverError(errInterface, strs...)
operatorLogger.Error(err)
telemetry.Error(err)
respondError(w, r, err)
}
}