- 在 GetLogin 和 PostLogin 函数中添加 return_url 参数 - 在 AuthRequired 中间件中添加重定向到登录页面的逻辑 - 修改登录表单,添加隐藏的 return_url 字段 - 优化错误处理,保留 return_url 以便登录失败后重新显示
27 lines
553 B
Go
27 lines
553 B
Go
package middleware
|
||
|
||
import (
|
||
"net/http"
|
||
"net/url"
|
||
|
||
"github.com/gin-contrib/sessions"
|
||
"github.com/gin-gonic/gin"
|
||
)
|
||
|
||
func AuthRequired() gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
session := sessions.Default(c)
|
||
user := session.Get("user")
|
||
if user == nil {
|
||
// 获取当前请求的完整URL
|
||
returnURL := c.Request.URL.String()
|
||
// URL编码处理,避免特殊字符造成问题
|
||
encodedURL := url.QueryEscape(returnURL)
|
||
c.Redirect(http.StatusFound, "/login?return_url="+encodedURL)
|
||
c.Abort()
|
||
return
|
||
}
|
||
c.Next()
|
||
}
|
||
}
|