github.com/iron-io/functions@v0.0.0-20180820112432-d59d7d1c40b2/api/server/special_handler.go (about) 1 package server 2 3 import ( 4 "context" 5 "errors" 6 "net/http" 7 ) 8 9 var ErrNoSpecialHandlerFound = errors.New("Path not found") 10 11 type SpecialHandler interface { 12 Handle(c HandlerContext) error 13 } 14 15 // Each handler can modify the context here so when it gets passed along, it will use the new info. 16 type HandlerContext interface { 17 // Context return the context object 18 Context() context.Context 19 20 // Request returns the underlying http.Request object 21 Request() *http.Request 22 23 // Response returns the http.ResponseWriter 24 Response() http.ResponseWriter 25 26 // Overwrite value in the context 27 Set(key string, value interface{}) 28 } 29 30 type SpecialHandlerContext struct { 31 request *http.Request 32 response http.ResponseWriter 33 ctx context.Context 34 } 35 36 func (c *SpecialHandlerContext) Context() context.Context { 37 return c.ctx 38 } 39 40 func (c *SpecialHandlerContext) Request() *http.Request { 41 return c.request 42 } 43 44 func (c *SpecialHandlerContext) Response() http.ResponseWriter { 45 return c.response 46 } 47 48 func (c *SpecialHandlerContext) Set(key string, value interface{}) { 49 c.ctx = context.WithValue(c.ctx, key, value) 50 } 51 52 func (s *Server) AddSpecialHandler(handler SpecialHandler) { 53 s.specialHandlers = append(s.specialHandlers, handler) 54 } 55 56 // UseSpecialHandlers execute all special handlers 57 func (s *Server) UseSpecialHandlers(ctx context.Context, req *http.Request, resp http.ResponseWriter) (context.Context, error) { 58 if len(s.specialHandlers) == 0 { 59 return ctx, ErrNoSpecialHandlerFound 60 } 61 62 c := &SpecialHandlerContext{ 63 request: req, 64 response: resp, 65 ctx: ctx, 66 } 67 for _, l := range s.specialHandlers { 68 err := l.Handle(c) 69 if err != nil { 70 return c.ctx, err 71 } 72 } 73 return c.ctx, nil 74 }