我正在开发一个Web聊天应用程序,但遇到了不应发生的问题。
在main.go中,我具有以下功能:
http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
并且我刚刚用cookie构建了一个身份验证文件(auth.go,仍在进行中),它是:
package main
import "net/http"
type authHandler struct {
next http.Handler
}
func (h *authHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
_, err := r.Cookie("auth")
if err == http.ErrNoCookie {
//not authenticated
w.Header().Set("Location", "/login")
w.WriteHeader(http.StatusTemporaryRedirect)
return
}
if err != nil {
//some other error
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//success - call the next handler
h.next.ServeHTTP(w, r)
}
func MustAuth(handler http.Handler) http.Handler {
return &authHandler{next: handler}
}
问题是,当我运行它并打开localhost页面时,该cookie无法正常工作,也无法按我的意愿将其重定向到登录页面。
最佳答案
我已经根据您提供的代码制作了一个完整的编译示例-但是它确实对我有用:lolcalhost:8080/chat
将我重定向到localhost:8080/login
我怀疑您的浏览器可能已经设置了cookie“auth”。
您可以按STRG + SHIFT + I并转到“网络”选项卡以查看传输的内容。
检查是否确实没有为您设置cookie。
我试过的代码:
package main
import "net/http"
type authHandler struct {
next http.Handler
}
func ServeHTTP(w http.ResponseWriter, r *http.Request) {
_, err := r.Cookie("auth")
if err == http.ErrNoCookie {
//not authenticated
w.Header().Set("Location", "/login")
w.WriteHeader(http.StatusTemporaryRedirect)
return
}
if err != nil {
//some other error
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//success - call the next handler
//h.next.ServeHTTP(w, r)
w.Write([]byte("Hi"))
}
func main() {
http.HandleFunc("/chat", ServeHTTP)
http.ListenAndServe(":8080", nil)
}
关于http - 没有错误,但Go应用仍然无法正常运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62107287/