中间件代码:
func MiddlewareCors() middleware.Middleware {
return func(handler middleware.Handler) middleware.Handler {
return func(ctx context.Context, req interface{}) (interface{}, error) {
if ts, ok := transport.FromServerContext(ctx); ok {
if ht, ok := ts.(http.Transporter); ok {
method := ht.Request().Method
origin := ht.RequestHeader().Get("Origin")
if method == nethttp.MethodOptions {
ht.RequestHeader().Set("Access-Control-Allow-Origin", origin)
ht.RequestHeader().Set("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,PATCH,DELETE")
ht.RequestHeader().Set("Access-Control-Allow-Credentials", "true")
ht.RequestHeader().Set("Access-Control-Allow-Headers", "Content-Type,"+
"X-Requested-With,Access-Control-Allow-Credentials,User-Agent,Content-Length,Authorization")
}
}
}
return handler(ctx, req)
}
}
}
注册中间件
func NewHTTPServer(...) *http.Server {
var opts = []http.ServerOption{
http.Middleware(
...,
selector.Server(MiddlewareCors()).Build(),
...,
),
}
opts = append(opts, http.Network("0.0.0.0"))
opts = append(opts, http.Address("8080"))
opts = append(opts, http.Timeout(...)
srv := http.NewServer(opts...)
xxx.RegisterxxxHTTPServer(srv, xxx)
return srv
}
|