【问题标题】:Redirection to a page issue in Go [duplicate]重定向到 Go 中的页面问题 [重复]
【发布时间】:2018-02-09 01:06:42
【问题描述】:

我正在通过 go 服务 index.html。但是,根据将通过页面发送的某些参数,go 应该成功地重定向到不同的页面。尝试执行代码时出现以下错误。

http:多个 response.WriteHeader 调用

func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

    http.ServeFile(w, r, r.URL.Path[1:])
    fmt.Println(r.FormValue("login"))

    if r.FormValue("signup") == "signup" {
        signup(w, r)
    } else if r.FormValue("login") == "login" {
        if login(w, r) {
            if r.Method == "POST" {
                fmt.Println("I m here")
                http.Redirect(w, r, "http://localhost:8080/home.html" (http://localhost:8080/home.html') , http.StatusSeeOther)
            }

        }

    }

})
var port string
if port = os.Getenv("PORT"); len(port) == 0 {
    port = DEFAULT_PORT
}
log.Fatal(http.ListenAndServe(":"+port, nil))
}

【问题讨论】:

  • 您无法使用 ServeFile,然后尝试重定向。每个 HTTP 请求都可以只回答一次,发送重定向就是一个回答。
  • 在stackoverflow上搜索你的错误(上面加粗),你会发现很多相同问题的插图。

标签: go ibm-cloud


【解决方案1】:

正如 cmets 中已经提到并在错误消息中暗示的那样, 您不能两次更改响应标头:

  • http.ServeFile(w, r, r.URL.Path[1:]) 被调用时,w.WriteHeader(statusCode) 将被调用。换句话说,HTTP 响应将以statusCode 作为状态码发送。
  • singuphttp.Redirect 在调用 w.WriteHeader 后发送 HTTP 响应。

因此,应该发送哪个响应非常令人困惑。 您可能需要先检查signuplogin,如果没有,请致电http.ServeFile

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    fmt.Println(r.FormValue("login"))
    switch {
    case r.FormValue("signup") == "signup":
        signup(w, r)
    case r.FormValue("login") == "login" && login(w,r):
        if r.Method == "POST" {
            fmt.Println("I m here")
            http.Redirect(w, r, "http://localhost:8080/home.html" (http://localhost:8080/home.html') , http.StatusSeeOther)
    default:
        http.ServeFile(w, r, r.URL.Path[1:])
    }
})

更多关于why WriteHeader is warning you about this的信息来自a probably duplicated thread

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    • 2011-10-02
    • 1970-01-01
    • 2013-11-18
    • 2011-08-21
    相关资源
    最近更新 更多