1 回答
TA贡献1859条经验 获得超6个赞
有很多方法可以解决这个问题,其中一种是否完全“更好”是有争议的。我强烈建议编写一些中间件来包装您的路由并强制执行检查,仅在成功时调用包装的处理程序。
请注意,我将在这里做一些假设,因为您没有告诉我们您如何管理会话(cookies?服务器端?)和/或除了身份验证之外您可能需要什么样的授权。
// Middleware - a function that sits in the 'middle' of your request processing.
func RequireAuth(h http.Handler) http.Handler) {
fn := func(w http.ResponseWriter, r *http.Request) {
// Assuming gorilla/sessions
session, err := store.Get("name", r)
if err != nil {
// Raise HTTP 500
return
}
// We'll assume you're storing the userID in the cookie|server session
// upon login elsewhere.
id := session.Values["userID"]
// Probably returns a *yourapp.User
user, err := db.GetUser(id)
if err != nil {
// Raise HTTP 500
return
}
if user == nil {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
// Don't forget these 'naked' returns - if you miss one, your
// handler will keep processing beyond the error and result in
// unintended side effects
return
}
// Further checks here - i.e. checking user.Active == true, etc.
// The userID matches one in the DB, so let's proceed
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
// And in your router - assuming just vanilla net/http
http.Handle("/", RequireAuth(yourHandlerFunc))
http.Handle("/", RequireAuth(someOtherHandler))
// Note that using gorilla/mux or goji can help give you "subrouters" so you
// don't have to wrap every single route with your middleware (messy, error prone)
我还建议您阅读有关 Go 中间件1组合2 的一些内容,这将对您将来有所帮助。
如果您想调用自定义错误页面,只需编写一个处理程序 - 例如UnauthorizedHandler,满足 http.Handler 并且只是调用UnauthorizedHandler.ServeHTTP(w, r)而不是http.Error沿途调用。
- 1 回答
- 0 关注
- 156 浏览
添加回答
举报