V
V
v- death2015-10-23 19:57:47
go
v- death, 2015-10-23 19:57:47

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

status.go
pastebin.com/zMXdargE
router.go
pastebin.com/QzrvJMCw
If ps.ByName("methods") is not in the database, then it writes to the terminal
2015/10/23 15:48:11 http: multiple response.WriteHeader calls

I suspect that it is necessary in the design
if err = rows.Err(); err != nil {
    status.Code503(w, r)
  }

how to stop further execution of the function.
Three questions arise.
1. How to fix the function?
2. How to stop the execution of any function anywhere?
3. How to get rid of the design
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

1 answer(s)
A
Alexander Pavlyuk, 2015-10-23
@vGrabko99

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 question

Ask a Question

731 491 924 answers to any question