优化结构

This commit is contained in:
Yvan
2026-08-28 11:51:37 +08:00
parent 5b04998731
commit 33ba777137
25 changed files with 163 additions and 125 deletions
+6 -6
View File
@@ -12,9 +12,8 @@ import (
)
const (
CodeSuccess = 0
CodeError = 7
CodePasswordChangeRequired = 10001
CodeSuccess = 0
CodeError = 7
)
type Response struct {
@@ -55,12 +54,13 @@ func requestUsesHTTPS(request *http.Request) bool {
return strings.EqualFold(strings.TrimSpace(forwarded), "https")
}
// SetTokenCookie is the shared transport-level cookie policy for the admin API.
func SetTokenCookie(c *gin.Context, value string, maxAge int) {
// 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: "x-token", Value: value, Path: "/", MaxAge: maxAge, Secure: requestUsesHTTPS(c.Request), HttpOnly: true, SameSite: http.SameSiteStrictMode}
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)
}
+13
View File
@@ -2,6 +2,7 @@ package httpx
import (
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
@@ -31,3 +32,15 @@ func TestResponseHelpers(t *testing.T) {
}
}
}
func TestSetCookieUsesRequestedName(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.GET("/cookie", func(c *gin.Context) { SetCookie(c, "example", "value", 60) })
req := httptest.NewRequest("GET", "/cookie", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if got := w.Header().Get("Set-Cookie"); !strings.HasPrefix(got, "example=") {
t.Fatalf("Set-Cookie = %q", got)
}
}