// internal/server/http/http.go
package http
import (
"context"
"net/http"
"github.com/go-kratos/kratos/v2/middleware"
"github.com/go-kratos/kratos/v2/transport/http"
)
// CorsMiddleware is a simple CORS middleware.
func CorsMiddleware() middleware.Middleware {
return func(handler http.Handler) http.Handler {
return http.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
// 允许所有来源
w.Header().Set("Access-Control-Allow-Origin", "*")
// 允许指定的方法
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
// 允许指定的头部信息
w.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Authorization")
// 允许包含凭证信息
w.Header().Set("Access-Control-Allow-Credentials", "true")
// 处理预检请求(OPTIONS请求)
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusNoContent)
return
}
// 继续处理正常请求
handler.ServeHTTP(ctx, w, r)
})
}
}
// NewHTTPServer creates a new HTTP server instance.
func NewHTTPServer(srv *service.Service, opts ...http.ServerOption) *http.Server {
engine := http.NewServer(opts...)
// 添加跨域中间件
engine.Use(CorsMiddleware())
v1.RegisterGreeterHTTPServer(engine, srv)
return engine
}
kratos 跨域处理
最新推荐文章于 2024-07-24 06:27:02 发布