package middleware import ( "net/http" "strings" "github.com/gin-gonic/gin" ) // TokenAuth 校验请求头中的 X-Auth-Token 或 Authorization: Bearer . func TokenAuth(expected string) gin.HandlerFunc { return func(c *gin.Context) { got := c.GetHeader("X-Auth-Token") if got == "" { auth := c.GetHeader("Authorization") got = strings.TrimPrefix(auth, "Bearer ") } if got == "" || got != expected { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) return } c.Next() } }