forked from Altinity/clickhouse-backup
/
utils.go
87 lines (80 loc) · 2.56 KB
/
utils.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
83
84
85
86
87
package server
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
)
func (api *APIServer) flushOutput(w http.ResponseWriter, out string) {
if _, err := fmt.Fprintln(w, out); err != nil {
api.log.Warnf("can't write to http.ResponseWriter: %v", err)
}
}
func (api *APIServer) writeError(w http.ResponseWriter, statusCode int, operation string, err error) {
api.log.Errorf("api.writeError status=%d operation=%s err=%v", statusCode, operation, err)
w.WriteHeader(statusCode)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate")
w.Header().Set("Pragma", "no-cache")
out, _ := json.Marshal(struct {
Status string `json:"status"`
Operation string `json:"operation,omitempty"`
Error string `json:"error"`
}{
Status: "error",
Operation: operation,
Error: err.Error(),
})
api.flushOutput(w, string(out))
}
func (api *APIServer) sendJSONEachRow(w http.ResponseWriter, statusCode int, v interface{}) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate")
w.Header().Set("Pragma", "no-cache")
w.WriteHeader(statusCode)
switch reflect.TypeOf(v).Kind() {
case reflect.Slice:
s := reflect.ValueOf(v)
for i := 0; i < s.Len(); i++ {
if out, err := json.Marshal(s.Index(i).Interface()); err == nil {
api.flushOutput(w, string(out))
} else {
api.flushOutput(w, err.Error())
api.log.Warnf("sendJSONEachRow json.Marshal error: %v", err)
}
}
default:
if out, err := json.Marshal(v); err == nil {
api.flushOutput(w, string(out))
} else {
api.flushOutput(w, err.Error())
api.log.Warnf("sendJSONEachRow json.Marshal error: %v", err)
}
}
}
// CallbackResponse is the response that is returned to callers
type CallbackResponse struct {
Status string `json:"status"`
Error string `json:"error"`
}
// errorCallback executes callbacks with a payload notifying callers that the operation has failed
func (api *APIServer) errorCallback(ctx context.Context, err error, callback callbackFn) {
payload := &CallbackResponse{
Status: "error",
Error: err.Error(),
}
for _, e := range callback(ctx, payload) {
api.log.Error(e.Error())
}
}
// successCallback executes callbacks with a payload notifying callers that the operation succeeded
func (api *APIServer) successCallback(ctx context.Context, callback callbackFn) {
payload := &CallbackResponse{
Status: "success",
Error: "",
}
for _, e := range callback(ctx, payload) {
api.log.Error(e.Error())
}
}