[英]How to add custom http header in go fasthttp ?
我正在使用fasthttp服務器https://github.com/valyala/fasthttp
我需要為所有請求添加自定義標頭
Access-Control-Allow-Origin: *
我怎樣才能做到這一點 ?
由於它是一個響應頭,因此我假設您的意思是:
ctx.Response.Header.Set("Access-Control-Allow-Origin", "*")
如果您不使用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
本質上是參數HandlerFunc
h
HandlerFunc
。 組裝路線時,您可以執行以下操作:
http.HandleFunc("/api/endpoint", setResponseHeader(myHandlerFunc))
http.ListenAndServe(":8000", nil)
要在fasthttp上啟用CORS支持,最好使用fasthttpcors包。
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)))
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.