优化结构
This commit is contained in:
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user