2016-11-14 22 views
0

我目前收到此http: multiple response.WriteHeader calls錯誤,同時嘗試發送迴應給Angular。我正在做的主要事情是從Angular向Go發送一個請求。然後將接收到的數據插入到mongoDB中,但如果用戶名已存在,我將更改dup="true"並嘗試發送自定義響應。http:multiple response.WriteHeader調用

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

+5

'ExecuteTemplate'寫的響應呈現模板;如果'dup ==「true」',那麼你不能在那之後寫另一個響應頭。您也不希望在Web服務器中使用'log.Fatal',因爲一個請求錯誤可能會導致服務器崩潰。 – JimB

回答

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("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()) 
+0

非常感謝您的讚賞 – Racket