first commit

This commit is contained in:
Yangtao
2025-11-18 17:48:20 +08:00
commit 6e56cab848
196 changed files with 65809 additions and 0 deletions

View File

@ -0,0 +1,30 @@
package middleware
import (
"github.com/anxpp/common-utils/logg"
"github.com/anxpp/common-utils/net"
"github.com/gin-gonic/gin"
"net/http"
"net/url"
)
func Authorize() gin.HandlerFunc {
return func(c *gin.Context) {
inputToken := c.Request.Header.Get("X-Token")
if len(inputToken) == 0 {
c.JSON(http.StatusOK, net.Custom(500, "缺少授权token"))
c.Abort()
}
c.Next()
}
}
func LogRequest() gin.HandlerFunc {
return func(c *gin.Context) {
decodedStr, _ := url.QueryUnescape(c.Request.RequestURI)
logg.Info("request:", c.Request.RemoteAddr, decodedStr)
c.Next()
}
}

25
pkg/middleware/cors.go Normal file
View File

@ -0,0 +1,25 @@
package middleware
import (
"github.com/gin-gonic/gin"
"net/http"
)
// 处理跨域请求,支持options访问
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
c.Header("Access-Control-Allow-Origin", "*") // 可将将 * 替换为指定的域名
c.Header("Access-Control-Allow-Headers", "Content-Type,X-TOKEN") //你想放行的header也可以在后面自行添加
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS") //我自己只使用 get post 所以只放行它
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
c.Header("Access-Control-Allow-Credentials", "true")
// 放行所有OPTIONS方法
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
}
// 处理请求
c.Next()
}
}

View File

@ -0,0 +1,35 @@
package middleware
import (
"github.com/gin-gonic/gin"
"net/http"
"runtime/debug"
)
func Recover(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
debug.PrintStack()
c.JSON(http.StatusOK, gin.H{
"code": 500,
"message": "系统异常",
"detailError": errorToString(r),
"data": nil,
})
c.Abort()
}
}()
c.Next()
}
func errorToString(r interface{}) string {
switch v := r.(type) {
case error:
return v.Error()
default:
return r.(string)
}
}