import (
"net/http"
"github.com/zeromicro/go-zero/rest"
)
func add_router(method_type string, path string, handler http.HandlerFunc) rest.Route {
return rest.Route{
Method: method_type,
Path: "api/admin/" + path,
Handler: handler,
}
}
r = []rest.Route{
/*++++++++++++++++++++++++++++++会员部分++++++++++++++++++++++++*/
add_router(types.POST, "/members/list", response.WrapResponse(MembersList,login_chk.RouterCheckToken)),
}
return r
}
RouterCheckToken函数定义:
func (l *Login) RouterCheckToken(r *http.Request)(err error){
authorization := (*r).Header.Get(types.HEADER_AUTH)
exists,err := l.CheckToken(&authorization);
if err != nil{
return
}
if !exists{
//302跳转
return response.NewErrCodeMsg(200, "已过期,请通过refresh_token获取token或重新登录")
}
return
}
RouterCheckToken是校验是否登录的函数,如果过期返回错误消息,我想把他改造成过期了302跳转到登录页,应该怎么做
go zero 发起302跳转
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
2条回答 默认 最新
关注让【宝码香车】来帮您解答,本回答参考DeepSeek编写,并整理提供。
如果答案能帮助您,请采纳,非常感谢!
.
每日一句正能量,让它带给您好心情:把日子过得有滋有味,就是对生活最好的回馈。
.在 Go-Zero 中实现 302 跳转,你需要在
RouterCheckToken函数中直接操作 HTTP 响应。以下是修改方案:修改后的 RouterCheckToken 函数
func (l *Login) RouterCheckToken(w http.ResponseWriter, r *http.Request) error { authorization := r.Header.Get(types.HEADER_AUTH) exists, err := l.CheckToken(&authorization) if err != nil { return err } if !exists { // 302 跳转到登录页 http.Redirect(w, r, "/login", http.StatusFound) return nil } return nil }路由定义需要相应调整
func add_router(method_type string, path string, handler http.HandlerFunc) rest.Route { return rest.Route{ Method: method_type, Path: "api/admin/" + path, Handler: handler, } } r = []rest.Route{ /*++++++++++++++++++++++++++++++会员部分++++++++++++++++++++++++*/ add_router(types.POST, "/members/list", response.WrapResponse(MembersList, login_chk.RouterCheckToken)), }关键修改点说明
- 函数签名变更:
RouterCheckToken现在需要接收http.ResponseWriter和*http.Request两个参数 - **使用
http.Redirect**:直接调用标准库的跳转函数 - **返回
nil**:跳转后直接返回,不再返回错误信息
注意事项
- 确保登录页面的路径
/login是正确的 - 如果需要携带原请求信息,可以在跳转 URL 中添加参数:
http.Redirect(w, r, "/login?redirect="+url.QueryEscape(r.URL.String()), http.StatusFound)- 如果
WrapResponse函数需要适配新的函数签名,可能还需要相应的调整
这样修改后,当 token 过期时,请求会自动 302 跳转到登录页面。
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报- 函数签名变更: