46 lines
2.3 KiB
Go
46 lines
2.3 KiB
Go
// Just for kratos post body with http query param
|
|
package xhttp
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/go-kratos/kratos/v2/middleware"
|
|
"github.com/go-kratos/kratos/v2/transport/http"
|
|
)
|
|
|
|
// Server returns a new server middleware for kratos http context.
|
|
func Server() middleware.Middleware {
|
|
return func(handler middleware.Handler) middleware.Handler {
|
|
return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
|
|
if c, ok := ctx.(http.Context); ok {
|
|
// c.Header().Set("Access-Control-Allow-Origin", "*")
|
|
// c.Header().Set("Access-Control-Allow-Origin", "*") // 这是允许访问所有域
|
|
// c.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE") //服务器支持的所有跨域请求的方法,为了避免浏览次请求的多次'预检'请求
|
|
// // header的类型
|
|
// c.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
|
|
// // 允许跨域设置 可以返回其他子段
|
|
// c.Header().Set("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar") // 跨域关键设置 让浏览器可以解析
|
|
// c.Header().Set("Access-Control-Max-Age", "172800") // 缓存请求信息 单位为秒
|
|
// c.Header().Set("Access-Control-Allow-Credentials", "false")
|
|
// c.Header().Set("content-type", "application/json") // 设置返回格式是json
|
|
ctx = RequestToContext(c)
|
|
}
|
|
return handler(ctx, req)
|
|
}
|
|
}
|
|
}
|
|
|
|
type httpReqKey struct{}
|
|
|
|
func RequestToContext(ctx http.Context) context.Context {
|
|
return context.WithValue(ctx, httpReqKey{}, ctx)
|
|
}
|
|
|
|
func RequestFromContext(ctx context.Context) http.Context {
|
|
c, ok := ctx.Value(httpReqKey{}).(http.Context)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
return c
|
|
}
|