33// license that can be found in the LICENSE file.
44
55/*
6- Package router 0.2.8 provides fast HTTP request router.
6+ Package router 0.2.9 provides fast HTTP request router.
77
88The router matches incoming requests by the request method and the path.
99If a handle is registered for this path and method, the router delegates the
@@ -67,6 +67,31 @@ Checks JSON Content-Type automatically:
6767 r.Listen(":8888")
6868 }
6969
70+ Custom handler with "Access-Control-Allow":
71+
72+ func baseHandler(handle router.Handle) router.Handle {
73+ return func(c *router.Control) {
74+ if origin := c.Request.Header.Get("Origin"); origin != "" {
75+ c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
76+ c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
77+ }
78+ handle(c)
79+ }
80+ }
81+
82+ func Hello(c *router.Control) {
83+ c.Body("Hello world")
84+ }
85+
86+ func main() {
87+ r := router.New()
88+ r.CustomHandler = baseHandler
89+ r.GET("/hello", Hello)
90+
91+ // Listen and serve on 0.0.0.0:8888
92+ r.Listen(":8888")
93+ }
94+
7095Go Router
7196*/
7297package router
@@ -92,6 +117,9 @@ type Router struct {
92117 // http status code http.StatusInternalServerError (500)
93118 PanicHandler Handle
94119
120+ // CustomHandler is called allways if defined
121+ CustomHandler func (Handle ) Handle
122+
95123 // Logger activates logging user function for each requests
96124 Logger Handle
97125}
@@ -192,7 +220,11 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
192220 if len (params ) > 0 {
193221 c .Params = append (c .Params , params ... )
194222 }
195- handle (c )
223+ if r .CustomHandler != nil {
224+ r .CustomHandler (handle )(c )
225+ } else {
226+ handle (c )
227+ }
196228 return
197229 }
198230 }
0 commit comments