-
Notifications
You must be signed in to change notification settings - Fork 0
/
gomple.go
69 lines (57 loc) · 1.27 KB
/
gomple.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
package gomple
import (
"bytes"
"encoding/json"
"io"
"net/http"
)
type HandlerFunc func(w http.ResponseWriter, r *http.Request) error
type ErrorHandler func(w http.ResponseWriter, r *http.Request, err error)
func DefaultErrorHandler(w http.ResponseWriter, r *http.Request, err error) {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
type config struct {
errHandler ErrorHandler
}
type Option func(cfg *config)
func WithErrorHandler(eh ErrorHandler) Option {
if eh == nil {
eh = DefaultErrorHandler
}
return func(cfg *config) {
cfg.errHandler = eh
}
}
func defaults() []Option {
return []Option{
WithErrorHandler(nil),
}
}
func New(opts ...Option) *Gomple {
cfg := new(config)
for _, opt := range append(defaults(), opts...) {
opt(cfg)
}
return &Gomple{
errHandler: cfg.errHandler,
}
}
type Gomple struct {
errHandler ErrorHandler
}
func (g *Gomple) WrapFunc(h HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := h(w, r); err != nil {
g.errHandler(w, r, err)
return
}
}
}
func (g *Gomple) JSON(w http.ResponseWriter, r *http.Request, j interface{}) {
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(j); err != nil {
g.errHandler(w, r, err)
return
}
_, _ = io.Copy(w, &buf)
}