-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler.go
97 lines (77 loc) · 1.79 KB
/
handler.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
package graceful
import (
"context"
"encoding/hex"
"io/ioutil"
"net/http"
"time"
"golang.org/x/net/trace"
"github.com/golang/glog"
)
type Handlerer interface {
http.Handler
Handle(string, http.Handler)
}
type lazyDumper []byte
func (d lazyDumper) String() string {
return hex.Dump(d)
}
func NewHandler(
codec Codec,
makebuf func() interface{},
process func(context.Context, interface{}) (interface{}, error)) http.HandlerFunc {
return http.HandlerFunc(
func(w http.ResponseWriter, req *http.Request) {
ts := time.Now()
tr := trace.New(req.URL.Path, req.URL.Path)
var err error
defer func() {
if err != nil {
tr.LazyPrintf("err: %v", err)
tr.SetError()
}
tr.Finish()
}()
ctx := req.Context()
select {
case <-ctx.Done():
Error(w, ctx.Err(), http.StatusInternalServerError)
return
default:
}
data, err := ioutil.ReadAll(req.Body)
if err != nil {
Error(w, err, http.StatusInternalServerError)
return
}
tr.LazyPrintf("raw: %v", lazyDumper(data))
if err = req.Body.Close(); err != nil {
Error(w, err, http.StatusInternalServerError)
return
}
args := makebuf()
if err = codec.Unmarshal(data, args); err != nil {
Error(w, err, http.StatusInternalServerError)
return
}
tr.LazyPrintf("req: %v", args)
resp, err := process(ctx, args)
if err != nil {
Error(w, err, http.StatusInternalServerError)
return
}
data, err = codec.Marshal(resp)
if err != nil {
Error(w, err, http.StatusInternalServerError)
return
}
tr.LazyPrintf("resp: %v", resp)
w.Header().Set("Content-Type", codec.MIME())
w.Header().Set("X-Timing", time.Since(ts).String())
w.WriteHeader(http.StatusOK)
if _, err = w.Write(data); err != nil {
glog.Error(err)
return
}
})
}