go - 重定向到 Go 中的页面问题

标签 go ibm-cloud

<分区>

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

http: 多次响应.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))
}

最佳答案

正如评论中已经提到的和错误消息中暗示的那样, 您不能两次更改响应 header :

  • 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

关于go - 重定向到 Go 中的页面问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45975293/

相关文章:

node.js - 如何使用node.js httpRequest连接到dashdb

go - 如何格式化time.Since().String()?

go - 升级 Go 后重新编译所有包?

Golang API - MySQL 连接但查询为空

smtp 无法在生产环境中工作,即使有凭据也未经过身份验证

php - IBM Bluemix PostgreSQL 和 psql

database - 如何使用 bool 属性检查运行查询

ios - 我如何将我的 ios 应用程序链接并同步到 cloudantnosqlite?

java - 如何在 Eclipse-Bluemix Liberty for Java 部署期间使用 list 的服务部分

postgresql - 创建指向现有实例的 bluemix postgresql 服务