简体   繁体   中英

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. The main thing I'm doing is sending a post request from Angular to 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.

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; if I use anything with write header I get the same 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.

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

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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