kra-new/internal/server/httpx/response.go

70 lines
2.0 KiB
Go

// Package httpx contains the stable JSON response contract shared by HTTP
// modules. It intentionally keeps the existing Gin adapter so callers can
// migrate without changing their handler flow.
package httpx
import (
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
)
const (
CodeSuccess = 0
CodeError = 7
CodePasswordChangeRequired = 10001
)
type Response struct {
Code int `json:"code"`
Data any `json:"data"`
Msg string `json:"msg"`
}
type PageResult struct {
List any `json:"list"`
Total int64 `json:"total"`
Page int `json:"page"`
PageSize int `json:"pageSize"`
}
func Write(c *gin.Context, code int, data any, message string) {
c.JSON(http.StatusOK, Response{Code: code, Data: data, Msg: message})
}
func OK(c *gin.Context) { Write(c, CodeSuccess, gin.H{}, "操作成功") }
func OKWithData(c *gin.Context, data any) { Write(c, CodeSuccess, data, "成功") }
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)
}