-
Notifications
You must be signed in to change notification settings - Fork 5
/
hoge.go
82 lines (68 loc) · 1.56 KB
/
hoge.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
package gen
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"github.com/gorilla/mux"
)
var _ = fmt.Print
type HogePostParamDataHandler func(
vars map[string]string,
param HogePostParam,
r *http.Request) (Hoge, error)
func init() {
addImplDef("/hoge", "POST")
}
func InjectHogePost(
router *mux.Router,
dh HogePostParamDataHandler,
middleware func(http.HandlerFunc) http.HandlerFunc,
) {
if dh == nil {
panic(errors.New("Nil handler passed to InjectHogePost !!!"))
}
handler := hogePostParamHandler(dh)
if middleware != nil {
handler = middleware(handler)
}
router.HandleFunc("/hoge", handler).Methods("POST")
markImpl("/hoge", "POST")
}
func hogePostParamHandler(dh HogePostParamDataHandler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var err error
defer handleRuntimeError(w)
var reqData HogePostParam
// 1. decode from json
if r.Body != nil {
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&reqData)
if err != nil {
SendError(w, NewAPIError(http.StatusBadRequest, "json parse error"))
return
}
}
// 2. validate request
if err := HogePostValidator.Validate(&reqData); err != nil {
SendError(w, validateError2APIError(err))
return
}
// 3. handle datas
vars := mux.Vars(r)
res, err := dh(vars, reqData, r)
if err != nil {
SendError(w, err)
return
}
// 5. encode to json
b, err := json.Marshal(&res)
if err != nil {
SendError(w, err)
return
}
// 6. send data
w.Header().Add("Content-Type", "application/json")
fmt.Fprintf(w, string(b))
}
}