-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
100 lines (85 loc) · 1.83 KB
/
middleware.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
98
99
100
package main
import (
"fmt"
"net/http"
"errors"
)
type Response struct {
statusCode int
body string
headers http.Header
}
func (r *Response) Write(w http.ResponseWriter) {
head := w.Header()
for k, _ := range r.headers {
head.Set(k, r.headers.Get(k))
}
w.WriteHeader(r.statusCode)
fmt.Fprint(w, r.body)
}
func ResponseFromError(err error) *Response {
return &Response{
statusCode: 500,
body: err.Error(),
}
}
type RequestHandler func(*http.Request) *Response
type ResponseHandler func(*Response) error
type Handler struct {
Requests []RequestHandler
Responses []ResponseHandler
Handler RequestHandler
}
func NewHandler() *Handler {
return &Handler{}
}
func (h *Handler) AddMiddleware(mid Middleware) error {
h.Requests = append(h.Requests, mid.GetRequest())
h.Responses = append(h.Responses, mid.GetResponse())
return nil
}
func (h *Handler) SetHandler(hand RequestHandler) error {
if h.Handler != nil {
return errors.New("Setting handler twice!!")
}
h.Handler = hand
return nil
}
func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
for _, reqHandler := range h.Requests {
resp := reqHandler(req)
if resp != nil {
resp.Write(w)
return
}
}
resp := h.Handler(req)
for _, respHandler := range h.Responses {
err := respHandler(resp)
if err != nil {
ResponseFromError(err).Write(w)
return
}
}
resp.Write(w)
}
type Middleware interface {
GetRequest() RequestHandler
GetResponse() ResponseHandler
}
type BasicMiddleware struct {
req RequestHandler
resp ResponseHandler
}
func (mid * BasicMiddleware) GetRequest() RequestHandler {
return mid.req
}
func (mid * BasicMiddleware) GetResponse() ResponseHandler {
return mid.resp
}
func NewBasicMiddleware(req RequestHandler, resp ResponseHandler) Middleware {
return &BasicMiddleware{
req: req,
resp: resp,
}
}