-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata.go
80 lines (63 loc) · 2.02 KB
/
data.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
package mohttp
import (
"golang.org/x/net/context"
)
var dataHandlerContext = NewContextValueStore("github.com/jonasi/http.DataHandler")
// A DataResponder is responsible for formatting the return values of a DataHandlerFunc
// onto the http Response
type DataResponder interface {
HandleErr(context.Context, error)
HandleResult(context.Context, interface{}) error
}
// GetDataResponder retrieves the current DataResponder, if it exists, from the context
func GetDataResponder(c context.Context) (DataResponder, bool) {
r, ok := dataHandlerContext.Get(c).(DataResponder)
return r, ok
}
// WithDataResponder returns a new context with the provided DataResponder set
func WithDataResponder(c context.Context, r DataResponder) context.Context {
return dataHandlerContext.Set(c, r)
}
// DataResponderHandler returns a Handler whose single responsibility is to set
// the provided DataResponder on the context
func DataResponderHandler(d DataResponder) Handler {
return HandlerFunc(func(c context.Context) {
c = WithDataResponder(c, d)
Next(c)
})
}
// A DataHandlerFunc is a Handle which separates out the logic of
// retrieving/returning data from the logic of formatting/serializing it
// on the wire
type DataHandlerFunc func(context.Context) (interface{}, error)
// Handle satisfies the Handler interface. If no DataResponder has been
// set on the context, this method will panic.
func (fn DataHandlerFunc) Handle(c context.Context) {
r, ok := dataHandlerContext.Get(c).(DataResponder)
if !ok {
panic("No DataResponder set in handler chain")
}
var (
err error
result interface{}
)
defer func() {
if err2 := recoverErr(); err2 != nil {
err = err2
}
if err == nil && result != DataNoBody {
err = r.HandleResult(c, result)
}
if err != nil {
r.HandleErr(c, err)
}
}()
result, err = fn(c)
}
func StaticDataHandler(v interface{}) DataHandlerFunc {
return DataHandlerFunc(func(c context.Context) (interface{}, error) {
return v, nil
})
}
var dataNoBody = struct{}{}
var DataNoBody interface{} = &dataNoBody