英文:
http: multiple response.WriteHeader calls
问题
我在尝试向Angular发送响应时遇到了http: multiple response.WriteHeader calls
错误。我主要是从Angular向Go发送了一个POST请求。然后,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)
只是一个示例;如果我使用任何带有写头的内容,都会出现相同的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
答案1
得分: 3
这行代码 err := tpl.ExecuteTemplate(w, "index.html", User{u, p, e, n})
应该是你最后要做的事情,因为它会写入你的响应。
如果你想处理在渲染 index.html
时可能遇到的任何错误,你可以通过传入一个 bytes.Buffer
来渲染模板。
buf := &bytes.Buffer{}
if err := tpl.ExecuteTemplate(buf, "index.html", User{u, p, e, n}); err != nil {
log.Printf("渲染 'index.html' 出错 - 错误信息: %v", err)
http.Error(w, "内部服务器错误", 500)
return
}
// 将渲染后的模板写入 ResponseWriter
w.Write(buf.Bytes())
英文:
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())
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论