优化结构

This commit is contained in:
Yvan
2026-08-23 01:31:48 +08:00
parent 4e5071ee65
commit b4d843290d
8 changed files with 133 additions and 68 deletions
+26
View File
@@ -5,6 +5,8 @@ package httpx
import (
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
)
@@ -41,3 +43,27 @@ func Fail(c *gin.Context, message string) { Write(c, CodeError, gin.H{}, message
func NoAuth(c *gin.Context, message string) {
c.AbortWithStatusJSON(http.StatusUnauthorized, Response{Code: CodeError, Data: nil, Msg: message})
}
func requestUsesHTTPS(request *http.Request) bool {
if request != nil && request.TLS != nil {
return true
}
if request == nil {
return false
}
forwarded := strings.SplitN(request.Header.Get("X-Forwarded-Proto"), ",", 2)[0]
return strings.EqualFold(strings.TrimSpace(forwarded), "https")
}
// SetTokenCookie is the shared transport-level cookie policy. It has no KRA
// business dependency, so handlers and middleware can use pkg/httpx directly.
func SetTokenCookie(c *gin.Context, value string, maxAge int) {
if c == nil {
return
}
cookie := &http.Cookie{Name: "x-token", Value: value, Path: "/", MaxAge: maxAge, Secure: requestUsesHTTPS(c.Request), HttpOnly: true, SameSite: http.SameSiteStrictMode}
if maxAge < 0 {
cookie.Expires = time.Unix(1, 0)
}
http.SetCookie(c.Writer, cookie)
}