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

86 lines
2.5 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
)
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) {
if code == CodeError {
message = sanitizeFailureMessage(message)
}
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 sanitizeFailureMessage(message string) string {
message = strings.TrimSpace(message)
lower := strings.ToLower(message)
for _, marker := range []string{"gorm", "sql:", "redis", "mysql", "mongo", "dial ", "connection", "provider", "sdk", "json:", "serialize", "timeout", "http 4", "http 5", "tls:", "record not found", "error 1062"} {
if strings.Contains(lower, marker) {
return "操作失败"
}
}
if strings.Contains(message, "失败:") {
return strings.TrimSpace(strings.SplitN(message, "失败:", 2)[0]) + "失败"
}
return 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")
}
// SetCookie applies the transport-level cookie policy without knowing the
// application's cookie names or authentication semantics.
func SetCookie(c *gin.Context, name, value string, maxAge int) {
if c == nil {
return
}
cookie := &http.Cookie{Name: name, 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)
}