CORS middleware for julienschmidt/httprouter with Golang
Sun, Apr 3, 2022 in post General Tips and Tricks golang httprouter cors access control
Just a small note / Gist type of thing for today: I got tired of adding w.Header().Set("Access-Control-Allow-Origin", "*")
to every handler function in my small Golang
web app. I'm using Julien Schmidt's excellent httprouter module for simple routing. Turns
out the Basic Authentication example is quite simple to adjust for a
set-and-forget type of httprouter.Handle
middleware:
// https://github.com/julienschmidt/httprouter middleware to set CORS header
func MiddleCORS(next httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter,
r *http.Request, ps httprouter.Params) {
w.Header().Set("Access-Control-Allow-Origin", "*")
next(w, r, ps)
}
}
Using the middleware is simple, just wrap your normal handler function:
router.GET("/someurl", MiddleCORS(SomeURLFunc))
Or both the middleware and the function it takes implement httprouter.Handle
, you can just chain multiple middleware with MiddleCORS(AnotherMiddleware(SomeURLFunc))
.