Skip to content

Commit

Permalink
add gin.middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
BreezeHubs committed Dec 14, 2022
1 parent ecb5832 commit a13f32a
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 0 deletions.
30 changes: 30 additions & 0 deletions gin/middleware/cors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package middleware

import (
"net/http"

"github.com/gin-gonic/gin"
)

func Cors(url ...string) gin.HandlerFunc {
urlStr := "*"
if len(url) > 0 {
urlStr = url[0]
}

return func(c *gin.Context) {
method := c.Request.Method
origin := c.Request.Header.Get("Origin")
if origin != "" {
c.Header("AccessControl-Allow-Origin", urlStr) // 可将将 * 替换为指定的域名
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, UT, DELETE, UPDATE")
c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Acept, Authorization")
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Alow-Headers, Cache-Control, Content-Language, Content-Type")
c.Header("Access-Control-Allow-Credentials", "true")
}
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
}
c.Next()
}
}
31 changes: 31 additions & 0 deletions gin/middleware/param.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package middleware

import (
"errors"
"reflect"

"github.com/go-playground/validator/v10"
)

// 自定义错误消息
func FilterBindErr(errs error, r any) error {
vErrs := errs.(validator.ValidationErrors)
s := reflect.TypeOf(r)
for _, fieldError := range vErrs {
filed, _ := s.FieldByName(fieldError.Field()) //用反射获取参数名

//获取对应binding得错误消息 tag:错误类型_err,如:required_err:"userId不能为空"`
if errTagText := filed.Tag.Get(fieldError.Tag() + "_err"); errTagText != "" {
return errors.New(errTagText)
}

//通用错误类型 tag:err,如:err:"userId错误"`
if errText := filed.Tag.Get("err"); errText != "" {
return errors.New(errText)
}

//无法匹配到错误,如:user的格式需遵守: required
return errors.New(fieldError.Field() + "的格式需遵守: " + fieldError.Tag())
}
return errors.New("")
}
32 changes: 32 additions & 0 deletions gin/middleware/recover.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package middleware

import (
"fmt"
"log"
"runtime/debug"

"github.com/gin-gonic/gin"
)

func Recover(stack bool) gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
var errStr string
if stack {
//打印错误堆栈信息
log.Printf("panic: %v\n", r)
debug.PrintStack()

errStr = "服务器内部错误" + fmt.Sprintf("panic: %v\n", r)
} else {
errStr = "服务器内部错误"
}

//封装通用json返回
c.JSON(500, gin.H{500, errStr, nil})
}
}()
c.Next()
}
}

0 comments on commit a13f32a

Please sign in to comment.