简体   繁体   English

http:多个响应。WriteHeader调用

[英]http: multiple response.WriteHeader calls

I am currently receiving this http: multiple response.WriteHeader calls error while trying to send back a response to Angular. 我目前正在收到此http: multiple response.WriteHeader calls尝试将响应发送回Angular时发生错误。 The main thing I'm doing is sending a post request from Angular to Go. 我正在做的主要事情是从Angular发送一个发布请求到Go。 Go then inserts the data received into mongoDB, but if the username already exists I change dup="true" and try to send a custom response. Go然后将接收到的数据插入mongoDB,但是如果用户名已经存在,我将更改dup="true"并尝试发送自定义响应。

func Register(w http.ResponseWriter, req *http.Request) {

u := req.FormValue("username")
p := req.FormValue("password")
e := req.FormValue("email")
n := req.FormValue("name")

err := tpl.ExecuteTemplate(w, "index.html", User{u, p, e, n})
if err != nil {
    http.Error(w, err.Error(), 500)
    log.Fatalln(err)
}

a := User{Username: u, Password: p, Email: e, Name: n}
if a.Username != "" || a.Password != "" || a.Email != "" || a.Name != "" {
    insert(a)
    if dup == "true" {
        w.WriteHeader(http.StatusInternalServerError)
    }
}}

w.WriteHeader(http.StatusInternalServerError) is just an example; w.WriteHeader(http.StatusInternalServerError)只是一个示例; if I use anything with write header I get the same http: multiple response.WriteHeader calls 如果我将任何内容与写入标头一起使用,则会得到相同的http: multiple response.WriteHeader calls

This line err := tpl.ExecuteTemplate(w, "index.html", User{u, p, e, n}) should be the last thing you do since it will write to your response. 这行err := tpl.ExecuteTemplate(w, "index.html", User{u, p, e, n})应该是您要做的最后一件事,因为它将写入响应中。

If you want to handle any potential errors that you may encounter when you render index.html you can render the template by passing in a bytes.Buffer 如果要处理呈现index.html时可能遇到的任何潜在错误,则可以通过传入bytes.Buffer来呈现模板。

buf := &bytes.Buffer{}
if err := tpl.ExecuteTemplate(buf, "index.html", User{u, p, e, n}); err != nil {
    log.Printf("Error rendering 'index.html' - error: %v", err)
    http.Error(w, "Internal Server Error", 500)
    return
}

// Write your rendered template to the ResponseWriter
w.Write(buf.Bytes())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM