http - 没有错误,但Go应用仍然无法正常运行

标签 http go redirect cookies localhost

我正在开发一个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/

相关文章:

jsf - 使用 ExternalContext.redirect() 将人脸消息添加到重定向页面

php - Apache 在发送 304 时忽略 PHP header

http - 处理 HTTPS 页面中的 HTTP 内容

http - 如何捕获提供 HTTP 响应的服务器的 IP 地址

macos - 有关详细信息,请参阅 : ’go help gopath’

redirect - nginx http 到 https 导致重定向过多

ruby-on-rails - 更改设备注册路径

angularjs - 如何在 AngularJs 中将重复的 header 发送到 $http?

email - 去smtp发邮件

go - 本地运行 Go Tour 时出错 : Couldn't find tour files: could not find go-tour content; check $GOROOT and $GOPATH