我使用的是fasthttp服务器https://github.com/valyala/fasthttp
我需要为所有请求添加自定义标头
Access-Control-Allow-Origin: *我该怎么做呢?
发布于 2018-06-22 16:22:01
因为它是一个响应头,所以我假设你是这个意思:
ctx.Response.Header.Set("Access-Control-Allow-Origin", "*")发布于 2018-06-23 06:13:42
不使用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的装饰者。当你组装你的路由时,你可以这样做:
http.HandleFunc("/api/endpoint", setResponseHeader(myHandlerFunc))
http.ListenAndServe(":8000", nil) 发布于 2019-02-26 05:25:24
要在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)))
}https://stackoverflow.com/questions/50983605
复制相似问题