This repository has been archived by the owner on Dec 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
246 lines (217 loc) · 5.94 KB
/
api.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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"sort"
"strings"
"github.com/adjust/goautoneg"
"github.com/pborman/uuid"
)
const (
RequestErrAccessDenied = "access_denied"
RequestErrInsufficient = "insufficient"
RequestErrOverflow = "overflow"
RequestErrInvalidValue = "invalid_value"
RequestErrInvalidFormat = "invalid_format"
RequestErrMissing = "missing"
RequestErrNotFound = "not_found"
RequestErrConflict = "conflict"
RequestErrActOfGod = "act_of_god"
)
var (
ActOfGodError = []RequestError{{Slug: RequestErrActOfGod}}
InvalidFormatError = []RequestError{{Slug: RequestErrInvalidFormat, Field: "/"}}
AccessDeniedError = []RequestError{{Slug: RequestErrAccessDenied}}
Encoders = []string{"application/json"}
ErrUserIDNotSet = errors.New("user ID not set")
ErrInvalidUUID = errors.New("not a valid uuid")
)
type RequestError struct {
Slug string `json:"error,omitempty"`
Field string `json:"field,omitempty"`
Param string `json:"param,omitempty"`
Header string `json:"header,omitempty"`
}
type UnhandledRequestError RequestError
func (u UnhandledRequestError) Error() string {
return fmt.Sprintf("unhandled RequestError %+v", u.RequestError())
}
func (u UnhandledRequestError) RequestError() RequestError {
return RequestError(u)
}
type ContextHandler func(context.Context, http.ResponseWriter, *http.Request)
func NegotiateMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Accept") != "" {
contentType := goautoneg.Negotiate(r.Header.Get("Accept"), Encoders)
if contentType == "" {
w.WriteHeader(http.StatusNotAcceptable)
w.Write([]byte("Unsupported content type requested: " + r.Header.Get("Accept")))
return
}
}
h.ServeHTTP(w, r)
})
}
func Encode(w http.ResponseWriter, r *http.Request, status int, resp interface{}) {
contentType := goautoneg.Negotiate(r.Header.Get("Accept"), Encoders)
w.Header().Set("content-type", contentType)
w.WriteHeader(status)
var err error
switch contentType {
case "application/json":
enc := json.NewEncoder(w)
err = enc.Encode(resp)
default:
enc := json.NewEncoder(w)
err = enc.Encode(resp)
}
if err != nil {
log.Println(err)
}
}
func Decode(r *http.Request, target interface{}) error {
defer r.Body.Close()
switch r.Header.Get("Content-Type") {
case "application/json":
dec := json.NewDecoder(r.Body)
return dec.Decode(target)
default:
dec := json.NewDecoder(r.Body)
return dec.Decode(target)
}
}
func CORSMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", r.Header.Get("Access-Control-Request-Headers"))
w.Header().Set("Access-Control-Allow-Credentials", "true")
if strings.ToLower(r.Method) == "options" {
methods := strings.Join(r.Header[http.CanonicalHeaderKey("Trout-Methods")], ", ")
w.Header().Set("Access-Control-Allow-Methods", methods)
w.Header().Set("Allow", methods)
w.WriteHeader(http.StatusOK)
return
}
h.ServeHTTP(w, r)
})
}
func ContextWrapper(c context.Context, handler ContextHandler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handler(c, w, r)
})
}
func CheckScopes(scopes []string, checking ...string) bool {
sort.Strings(scopes)
for _, scope := range checking {
found := sort.SearchStrings(scopes, scope)
if found == len(scopes) || scopes[found] != scope {
return false
}
}
return true
}
func GetScopes(r *http.Request) []string {
scopes := strings.Split(r.Header.Get("scopes"), " ")
for pos, scope := range scopes {
scopes[pos] = strings.TrimSpace(scope)
}
sort.Strings(scopes)
return scopes
}
func AuthUser(r *http.Request) (uuid.UUID, error) {
rawID := r.Header.Get("User-ID")
if rawID == "" {
return nil, ErrUserIDNotSet
}
id := uuid.Parse(rawID)
if id == nil {
return nil, ErrInvalidUUID
}
return id, nil
}
type ErrorDef struct {
Test func(*http.Response, RequestError) bool
Err error
}
func DecodeErrors(r *http.Response, errs []RequestError, defs []ErrorDef) []error {
var resp []error
for _, err := range errs {
var handled bool
for _, def := range defs {
if def.Test(r, err) {
resp = append(resp, def.Err)
handled = true
}
}
if !handled {
resp = append(resp, UnhandledRequestError(err))
}
}
return resp
}
func ErrorDefCodeFieldSlug(code int, field, slug string) func(*http.Response, RequestError) bool {
return func(r *http.Response, err RequestError) bool {
if r.StatusCode != code {
return false
}
if err.Field != field {
return false
}
if err.Slug != slug {
return false
}
return true
}
}
func ErrDefCodeParamSlug(code int, param, slug string) func(*http.Response, RequestError) bool {
return func(r *http.Response, err RequestError) bool {
if r.StatusCode != code {
return false
}
if err.Param != param {
return false
}
if err.Slug != slug {
return false
}
return true
}
}
func ActOfGodDef(r *http.Response, err RequestError) bool {
if r.StatusCode < 500 {
return false
}
if err.Field != "/" && err.Field != "" {
return false
}
if err.Slug != RequestErrActOfGod {
return false
}
return true
}
func InvalidFormatDef(r *http.Response, err RequestError) bool {
if r.StatusCode != 400 {
return false
}
if err.Field != "/" && err.Field != "" {
return false
}
if err.Slug != RequestErrInvalidFormat {
return false
}
return true
}
func ParamNotFoundDef(param string) func(*http.Response, RequestError) bool {
return ErrDefCodeParamSlug(404, param, RequestErrNotFound)
}
func ParamInvalidValueDef(param string) func(*http.Response, RequestError) bool {
return ErrDefCodeParamSlug(400, param, RequestErrInvalidValue)
}
func ParamInvalidFormatDef(param string) func(*http.Response, RequestError) bool {
return ErrDefCodeParamSlug(400, param, RequestErrInvalidFormat)
}