加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
method_override.go 1.55 KB
一键复制 编辑 原始数据 按行查看 历史
aesoper 提交于 2020-05-20 15:06 . 添加日志中间件
/**
* @Author: aesoper
* @Description: 请求方法重写中间件
* @File: method_override
* @Version: 1.0.0
* @Date: 2020/5/19 19:01
*/
package gin_middleware
import (
"gitee.com/gin-ecosystem/gin-middleware/consts"
"github.com/gin-gonic/gin"
"net/http"
"strings"
)
type (
MethodOverrideConfig struct {
Skipper Skipper
Getter MethodOverrideGetter
}
MethodOverrideGetter func(ctx *gin.Context) string
)
var (
DefaultMethodOverrideConfig = MethodOverrideConfig{
Skipper: DefaultSkipper,
Getter: MethodFromHeader(consts.HeaderXHTTPMethodOverride),
}
)
func DefaultMethodOverride() gin.HandlerFunc {
return NewMethodOverride(DefaultMethodOverrideConfig)
}
func NewMethodOverride(config MethodOverrideConfig) gin.HandlerFunc {
// Defaults
if config.Skipper == nil {
config.Skipper = DefaultMethodOverrideConfig.Skipper
}
if config.Getter == nil {
config.Getter = DefaultMethodOverrideConfig.Getter
}
return func(ctx *gin.Context) {
if config.Skipper(ctx) {
ctx.Next()
return
}
req := ctx.Request
if req.Method == http.MethodPost {
m := config.Getter(ctx)
if m != "" {
req.Method = strings.ToUpper(m)
}
}
ctx.Next()
}
}
func MethodFromHeader(header string) MethodOverrideGetter {
return func(c *gin.Context) string {
return c.Request.Header.Get(header)
}
}
func MethodFromForm(param string) MethodOverrideGetter {
return func(c *gin.Context) string {
return c.PostForm(param)
}
}
func MethodFromQuery(param string) MethodOverrideGetter {
return func(c *gin.Context) string {
return c.Query(param)
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化