-
Notifications
You must be signed in to change notification settings - Fork 0
/
special_handler.go
74 lines (59 loc) · 1.65 KB
/
special_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
package server
import (
"context"
"errors"
"net/http"
)
var ErrNoSpecialHandlerFound = errors.New("Path not found")
type SpecialHandler interface {
Handle(c HandlerContext) error
}
// Each handler can modify the context here so when it gets passed along, it will use the new info.
type HandlerContext interface {
// Context return the context object
Context() context.Context
// Request returns the underlying http.Request object
Request() *http.Request
// Response returns the http.ResponseWriter
Response() http.ResponseWriter
// Overwrite value in the context
Set(key string, value interface{})
}
type SpecialHandlerContext struct {
request *http.Request
response http.ResponseWriter
ctx context.Context
}
func (c *SpecialHandlerContext) Context() context.Context {
return c.ctx
}
func (c *SpecialHandlerContext) Request() *http.Request {
return c.request
}
func (c *SpecialHandlerContext) Response() http.ResponseWriter {
return c.response
}
func (c *SpecialHandlerContext) Set(key string, value interface{}) {
c.ctx = context.WithValue(c.ctx, key, value)
}
func (s *Server) AddSpecialHandler(handler SpecialHandler) {
s.specialHandlers = append(s.specialHandlers, handler)
}
// UseSpecialHandlers execute all special handlers
func (s *Server) UseSpecialHandlers(ctx context.Context, req *http.Request, resp http.ResponseWriter) (context.Context, error) {
if len(s.specialHandlers) == 0 {
return ctx, ErrNoSpecialHandlerFound
}
c := &SpecialHandlerContext{
request: req,
response: resp,
ctx: ctx,
}
for _, l := range s.specialHandlers {
err := l.Handle(c)
if err != nil {
return c.ctx, err
}
}
return c.ctx, nil
}