title: How to handle superfluous response.WriteHeader call in order to return 500
body: <p>I am aware that the <code>WriteHeader</code> method of <a href="https://golang.org/pkg/net/http/#ResponseWriter" rel="noreferrer">http.ResponseWriter</a> can only be called once per HTTP response, can only have a single response status code and can only send the headers once. This is all perfectly fine.</p>
  
  <p>The question is, how should I refactor my code in order to override <code>201</code> and return <code>500</code> if <code>http.ResponseWriter.Write</code> returns an error? As you can see below I force panic on purpose to see how <a href="https://github.com/julienschmidt/httprouter/blob/master/router.go#L161" rel="noreferrer">httprouter.Router.PanicHandler</a> handles it. As expected, logs show <code>http: superfluous response.WriteHeader call from ...</code> and the response is <code>201</code> because it is too late as explained above.</p>
  
  <pre class="lang-golang prettyprint-override"><code>package server
  
  import (
      "github.com/julienschmidt/httprouter"
      "log"
      "net/http"
  )
  
  func Serve() {
      rtr := httprouter.New()
      rtr.GET("/", home.Welcome)
  
      handle500(rtr)
  
      err := http.ListenAndServe(":8080", rtr)
      if err != nil {
          log.Fatalf("server crash")
      }
  }
  
  func handle500(r *httprouter.Router) {
      r.PanicHandler = func(res http.ResponseWriter, req *http.Request, err interface{}) {
          res.WriteHeader(http.StatusInternalServerError)
          // http: superfluous response.WriteHeader call from line above
      }
  }
  </code></pre>
  
  <pre class="lang-golang prettyprint-override"><code>package home
  
  import (
      "github.com/julienschmidt/httprouter"
      "net/http"
  )
  
  func Welcome(res http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
      // doing a few bits and building the body
  
      res.Header().Set("Content-Type", "application/json")
      res.WriteHeader(201)
  
      _, err := res.Write("body goes here")
      if err == nil {  // I am doing this deliberately to test 500
          panic("assume that something has gone wrong with res.Write and an error occurred")
      }
  }
  </code></pre>