Reputation: 1193
I am using a fasthttp server https://github.com/valyala/fasthttp
I need to add a custom header for all requests
Access-Control-Allow-Origin: *
How can I do this ?
Upvotes: 1
Views: 2948
Reputation: 112
To enable CORS support on fasthttp, better use fasthttpcors package.
import (
...
cors "github.com/AdhityaRamadhanus/fasthttpcors"
...
)
func main() {
...
withCors := cors.NewCorsHandler(cors.Options{
AllowMaxAge: math.MaxInt32,
})
log.Fatal(fasthttp.ListenAndServe(":8080", withCors.CorsMiddleware(router.HandleRequest)))
}
Upvotes: 0
Reputation: 459
Another option if you are not using Context
:
func setResponseHeader(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
h.ServeHTTP(w, r)
}
}
setResponseHeader
is essentially a decorator of the argument HandlerFunc
h
. When you assemble your routes, you can do something like this:
http.HandleFunc("/api/endpoint", setResponseHeader(myHandlerFunc))
http.ListenAndServe(":8000", nil)
Upvotes: 0
Reputation: 1329
Since it's a response header i assume you mean this:
ctx.Response.Header.Set("Access-Control-Allow-Origin", "*")
Upvotes: 4