forked from cortezaproject/corteza
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
167 lines (139 loc) · 4.12 KB
/
http.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
package errors
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"sort"
"strings"
"syscall"
"github.com/cortezaproject/corteza-server/pkg/locale"
)
type (
translatable interface {
Translate(tr func(string, string, ...string) string) error
}
)
// ServeHTTP Prepares and encodes given error for HTTP transport
//
// mask arg hides extra/debug info
//
// Proper HTTP status codes are generally not used in the API due to compatibility issues
// This should be addressed in the future versions when/if we restructure the API
func ServeHTTP(w http.ResponseWriter, r *http.Request, err error, mask bool) {
// due to backward compatibility,
// custom HTTP statuses are disabled for now.
ServeHTTPWithCode(w, r, http.StatusOK, err, mask)
}
// ProperlyServeHTTP Prepares and encodes given error for HTTP transport, same as ServeHTTP but with proper status codes
func ProperlyServeHTTP(w http.ResponseWriter, r *http.Request, err error, mask bool) {
var (
code = http.StatusInternalServerError
)
if e, is := err.(*Error); is {
code = e.kind.httpStatus()
}
ServeHTTPWithCode(w, r, code, err, mask)
}
// Serves error via
func ServeHTTPWithCode(w http.ResponseWriter, r *http.Request, code int, err error, mask bool) {
var (
// Very naive approach on parsing accept headers
acceptsJson = strings.Contains(r.Header.Get("accept"), "application/json")
)
if !mask && !acceptsJson {
// Prettify error for plain text debug output
w.Header().Set("Content-Type", "plain/text")
w.WriteHeader(code)
writeHttpPlain(w, err, mask)
_, _ = fmt.Fprintln(w, "Note: you are seeing this because system is running in development mode")
_, _ = fmt.Fprintln(w, "and HTTP request is made without \"Accept: .../json\" headers")
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
writeHttpJSON(r.Context(), w, err, mask)
}
func writeHttpPlain(w io.Writer, err error, mask bool) {
var (
dlmt = strings.Repeat("-", 80)
write = func(s string, a ...interface{}) {
if _, err := fmt.Fprintf(w, s, a...); err != nil {
panic(fmt.Errorf("failed to write HTTP response: %w", err))
}
}
)
// handle client-aborted connections with no output
if errors.Is(err, syscall.EPIPE) || errors.Is(err, syscall.ECONNRESET) {
return
}
write("Error: ")
write(err.Error())
write("\n")
if _, is := err.(interface{ Safe() bool }); !is || mask {
// do not output any details on un-safe errors or
// when a masked output is preferred
return
}
if err, is := err.(*Error); is {
write(dlmt + "\n")
var (
ml, kk = err.meta.StringKeys()
)
sort.Strings(kk)
for _, key := range kk {
write("%s:", key)
write(strings.Repeat(" ", ml-len(key)+1))
write("%v\n", err.meta[key])
}
if len(err.stack) > 0 {
write(dlmt + "\n")
write("Call stack:\n")
for i, f := range err.stack {
write("%3d. %s:%d\n %s()\n", len(err.stack)-i, f.File, f.Line, f.Func)
}
}
if we := err.Unwrap(); we != nil {
write(dlmt + "\n")
write("Wrapped error:\n\n")
writeHttpPlain(w, we, mask)
}
}
write(dlmt + "\n")
}
// writeHttpJSON
func writeHttpJSON(ctx context.Context, w io.Writer, err error, mask bool) {
var (
wrap = struct {
Error interface{} `json:"error"`
}{}
)
// handle client-aborted connections with no output
if errors.Is(err, syscall.EPIPE) || errors.Is(err, syscall.ECONNRESET) {
return
}
if se, is := err.(interface{ Safe() bool }); !is || !se.Safe() || mask {
// trim error details when not debugging or error is not safe or maske
err = fmt.Errorf(err.Error())
}
// if error is translatable, pass in the lambda that returns
// translated error
//
// we're using global locale service directly for now
if tr, is := err.(translatable); is {
err = tr.Translate(func(ns string, key string, pairs ...string) string {
return locale.Global().T(ctx, ns, key, pairs...)
})
}
if c, is := err.(json.Marshaler); is {
// take advantage of JSON marshaller on error
wrap.Error = c
} else {
wrap.Error = map[string]string{"message": err.Error()}
}
if err = json.NewEncoder(w).Encode(wrap); err != nil {
panic(fmt.Errorf("failed to encode error: %w", err))
}
}