package api import ( "net/http" "time" "github.com/gin-gonic/gin" ) // SessionCookieName 会话 cookie 名称。 const SessionCookieName = "usernode_session" // SessionContextKey 会话在 gin context 中的键(router 中间件注入)。 const SessionContextKey = "auth_session" // setSessionCookie 写入会话 cookie(HttpOnly/SameSite=Lax;maxAge<=0 时清除)。 func setSessionCookie(c *gin.Context, sid string, ttl time.Duration, secure bool) { maxAge := int(ttl.Seconds()) if sid == "" { maxAge = -1 } http.SetCookie(c.Writer, &http.Cookie{ Name: SessionCookieName, Value: sid, Path: "/", HttpOnly: true, SameSite: http.SameSiteLaxMode, MaxAge: maxAge, Secure: secure, }) } // SessionIDFromCookie 从请求 cookie 读取会话 ID。 func SessionIDFromCookie(c *gin.Context) string { v, err := c.Cookie(SessionCookieName) if err != nil { return "" } return v }