Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is it possible to specify a list of headers which is going to be sent with each route? #31

Closed
salvador-dali opened this issue Jun 14, 2016 · 2 comments

Comments

@salvador-dali
Copy link

Currently in each route I have to write the following w.Header().Set("Content-Type", "application/javascript") at the beginning of every route. Is there a way to say: 'send this header before on each routes'?

P.S. thank you very much for excellent package.

@dimfeld
Copy link
Owner

dimfeld commented Jun 14, 2016

That's a bit outside of the scope of this package, but it's pretty easy to do by creating a small function to that will take a handler function as an argument and wrap the handler inside another function that writes the header and then calls the handler. Two ways of doing this are below:

func wrapHeader(handler httptreemux.HandlerFunc) httptreemux.HandlerFunc {
  return func(w http.ResponseWriter, r *http.Request, params map[string]string) {
    w.Header().Set("Content-Type", "application/javascript")
    handler(w, r, params)
   }
}

router.GET("/abc", wrapHeader(abcHandler))
router := httptreemux.New()
getWithHeader := func(path string, handler httptreemux.HandlerFunc) {
    wrappedHandler := func(w http.ResponseWriter, r *http.Request, params map[string]string) {
         w.Header().Set("Content-Type", "application/javascript")
         handler(w, r, params)
    }

   router.GET(path, wrappedHandler)
}

getWithHeader("/abc", abcHandler)

I haven't actually compiled these so there may be a bug or two, but hopefully this gives you the right idea.

@salvador-dali
Copy link
Author

I was aware of how to do this (still thank you for help). I thought that something like 'send all headers' already exist after seeing this api := router.NewGroup("/api/v1"), which is also can be achieved with a small function.

After looking through the package and not finding anything, I decided to ask you. Thank you very much for a reply.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants