duangua5308 2017-08-31 07:06
浏览 6
已采纳

转到Go中的页面问题[重复]

I am serving index.html through go. However, depending upon certain parameters that will be send through the page, go should redirect successfully to a different page. I am getting the below error while trying to execute the code.

http: multiple response.WriteHeader calls

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))
}
</div>
  • 写回答

1条回答 默认 最新

  • dsf8897 2017-08-31 09:00
    关注

    As already mentioned in the comments and implied in the error message, you can't change the response header twice:

    • When http.ServeFile(w, r, r.URL.Path[1:]) is called in some point w.WriteHeader(statusCode) will be called. In other words, an HTTP response will be sent with statusCode as status code.
    • singup or http.Redirect sends an HTTP response after calling w.WriteHeader.

    So it is very confusing which response should be sent. You may want to check signup and login first and if none then call 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:])
        }
    })
    

    More about why WriteHeader is warning you about this from a probably duplicated thread

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧