Answer the question
In order to leave comments, you need to log in
How to fix http:multiple response.WriteHeader calls?
Have a function
import (
"api/kernel/httprouter"
"api/kernel/status"
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"net/http"
)
func SelectMethods(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
rows, err := DB.Query("SELECT * FROM dev_method WHERE name=?", ps.ByName("methods"))
if err != nil {
status.Code503(w, r)
}
defer rows.Close()
bks := make([]*dev_method, 0)
for rows.Next() {
bk := new(dev_method)
err := rows.Scan(&bk.id, &bk.id_menu, &bk.name, &bk.description)
if err != nil {
status.Code503(w, r)
}
bks = append(bks, bk)
}
if err = rows.Err(); err != nil {
status.Code503(w, r)
}
i := 0
fmt.Fprintf(w, "{")
for _, bk := range bks {
i++
fmt.Fprintf(w, "'%s':['id_menu':'%s','name':'%s','description':'%s']", bk.id, bk.id_menu, bk.name, bk.description)
}
fmt.Fprintf(w, "}")
if i == 0 {
status.Code400(w, r)
}
}
2015/10/23 15:48:11 http: multiple response.WriteHeader calls
if err = rows.Err(); err != nil {
status.Code503(w, r)
}
i := 0
fmt.Fprintf(w, "{")
for _, bk := range bks {
i++
fmt.Fprintf(w, "'%s':['id_menu':'%s','name':'%s','description':'%s']", bk.id, bk.id_menu, bk.name, bk.description)
}
fmt.Fprintf(w, "}")
if i == 0 {
status.Code400(w, r)
}
? thanks in advance.
Answer the question
In order to leave comments, you need to log in
The error occurs because the response code must be written at most once and before writing the response body. Do a return on error, this will abort the function.
JSON is best generated using the encoding/json module, then get rid of this ugly construction.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question