-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.go
More file actions
91 lines (83 loc) · 2.43 KB
/
handler.go
File metadata and controls
91 lines (83 loc) · 2.43 KB
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
package jsonapi
import (
"encoding/json"
"fmt"
"net/http"
)
// Handler is easy to use entry for API developer.
//
// Just return something, and it will be encoded to JSON format and send to client.
// Or return an Error to specify http status code and error string.
//
// func myHandler(dec *json.Decoder, httpData *HTTP) (interface{}, error) {
// var param paramType
// if err := dec.Decode(¶m); err != nil {
// return nil, jsonapi.E400.SetData("You must send parameters in JSON format.")
// }
// return doSomething(param), nil
// }
//
// To redirect clients, return 301~303 status code and set Data property
//
// return nil, jsonapi.E301.SetData("http://google.com")
//
// Redirecting depends on http.Redirect(). The data returned from handler will never
// write to ResponseWriter.
//
// This basically obey the http://jsonapi.org rules:
//
// - Return {"data": your_data} if error == nil
// - Return {"errors": [{"code": application-defined-error-code, "detail": message}]} if error returned
type Handler func(r Request) (interface{}, error)
// ServeHTTP implements net/http.Handler
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
res, err := h(FromHTTP(w, r))
resp := make(map[string]interface{})
if err == nil {
resp["data"] = res
e := enc.Encode(resp)
if e == nil {
return
}
delete(resp, "data")
err = E500.SetOrigin(e).SetData(
`Failed to marshal data`,
)
}
code := http.StatusInternalServerError
if httperr, ok := err.(Error); ok {
if httperr.EqualTo(ASIS) {
if res != nil {
switch x := res.(type) {
case string:
w.Write([]byte(x))
case []byte:
w.Write(x)
case fmt.Stringer:
w.Write([]byte(x.String()))
default:
fmt.Fprintf(w, "%v", res)
}
}
return
}
code = httperr.Code
if code >= 301 && code <= 303 && httperr.location != "" {
// 301~303 redirect
http.Redirect(w, r, httperr.location, code)
return
}
w.WriteHeader(code)
resp["errors"] = []*ErrObj{fromError(&httperr)}
enc.Encode(resp)
return
}
w.WriteHeader(code)
resp["errors"] = []*ErrObj{{Detail: err.Error()}}
enc.Encode(resp)
}