title: How to do error http error handling in Go language
body: <p>I am little confused on how error handling should be done in go. I have read so many posts about it but still am not able to apply them on my structure of code. I am new to go so please help.</p>
  
  <p>There is a main function which handles two apis: api1 and api2</p>
  
  <pre><code>func main() {
      http.HandleFunc("/offers", api1)
      http.HandleFunc("/getOffersList", api2)
      err := http.ListenAndServe(":8080", nil)
      if err != nil {
          log.Fatal("ListenAndServe: ", err)
      }
  }
  
  
  func api1(w http.ResponseWriter, req *http.Request) {
      validateRequestHeader(w, req, "GET")
      // code here....
  }
  
  func api2(w http.ResponseWriter, req *http.Request) {
      validateRequestHeader(w, req, "POST")
      //code here....
  }
  
  func validateRequestHeader(w http.ResponseWriter, req *http.Request, allowedMethod string) {
      // allow cross domain AJAX requests
      w.Header().Set("Content-Type", "application/json")
      if origin := req.Header.Get("Origin"); origin != "" {
          w.Header().Set("Access-Control-Allow-Origin", origin)
          w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
          w.Header().Set("Access-Control-Allow-Headers",
              "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
      }
      // Stop here if its Preflighted OPTIONS request
      if req.Method == "OPTIONS" {
          return
      }
      if req.Method != allowedMethod {
          response := "Only " + allowedMethod + " requests are allowed"
          http.Error(w, response, http.StatusMethodNotAllowed)
          return
      }
  }
  </code></pre>
  
  <p>In both <code>api1</code> and <code>api2</code> , function <code>validateRequestHeader</code> is getting called. If this gets true, then in the api1/api2 further code is getting executed which I do not want. How it should be handled?</p>
  
  <pre><code>if req.Method != allowedMethod {
          response := "Only " + allowedMethod + " requests are allowed"
          http.Error(w, response, http.StatusMethodNotAllowed)
          return
      }
  </code></pre>