title: Preventing context deadline exceeded (Client.Timeout exceeded while awaiting headers) error with HTTP 200 OK
body: <p>I have a client and server. Server process the request more than 2 seconds. But client does not have so much time. It needs to get response in 1 seconds. That's why it responds with</p>
  <p><em>Get &quot;http://localhost:8888&quot;: context deadline exceeded (Client.Timeout exceeded while awaiting headers)
  panic: runtime error: invalid memory address or nil pointer dereference</em></p>
  <p>Question?
  How can I change server.go  in such a way that all errors are properly recovered
  and that the endpoint is always available?
  <strong>Note</strong> that the endpoint, the client is calling, should process request as quickly as possible and return a 200 OK as soon as it done.</p>
  <p>client.go</p>
  <pre><code>package main
  
  import (
      &quot;fmt&quot;
      &quot;log&quot;
      &quot;net/http&quot;
      &quot;time&quot;
  )
  
  func main() {
  
      c := &amp;http.Client{Timeout: 2 * time.Second}
  
      res, err := c.Get(&quot;http://localhost:8888&quot;)
      if err != nil {
          log.Println(err)
      }
      var r []byte
  
      _, err = res.Body.Read(r)
      fmt.Println(string(r))
  }
  </code></pre>
  <p>server.go</p>
  <pre><code>package main
  
  import (
      &quot;fmt&quot;
      &quot;io&quot;
      &quot;net/http&quot;
      &quot;time&quot;
  )
  
  func slowHandler(w http.ResponseWriter, req *http.Request) {
      time.Sleep(2 * time.Second)
      io.WriteString(w, &quot;I am slow!\n&quot;)
  }
  
  func main() {
      srv := http.Server{
          Addr:    &quot;:8888&quot;,
          Handler: http.HandlerFunc(slowHandler),
      }
  
      if err := srv.ListenAndServe(); err != nil {
          fmt.Printf(&quot;Server failed: %s\n&quot;, err)
      }
  }
  </code></pre>