title: http.Server ListenAndServer and then instant Shutdown doesn't work
body: <p>I'm trying to track down an issue in a larger program and wrote this small test program to help resolve it.</p>
  
  <p>If I start a http server and then instantly try to shut it down it doesn't shutdown and continues to serve requests. I can reason about the behavior but can't work out a way around it. I'm assuming it's because the server hasn't fully started up before I try to shut it down and so the shutdown fails and the startup continues and then finishes leaving it to serve requests as normal.</p>
  
  <p>How can I ensure the server is in a state that it can be shutdown before I call shutdown? If you comment out the sleep function between starting and stopping the server you will see it works as desired.</p>
  
  <pre><code>package main
  
  import (
      "context"
      "fmt"
      "io"
      "log"
      "net/http"
      "os"
      "os/signal"
      "time"
  )
  
  func main() {
      // stop on ^c
      quit := make(chan os.Signal)
      signal.Notify(quit, os.Interrupt)
  
      // router
      mux := http.NewServeMux()
      mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
          fmt.Println("serving request")
          io.WriteString(w, "Hello, world!\n")
      })
  
      // start server
      srv := &amp;http.Server{Addr: ":8080", Handler: mux}
      go func() {
          if err := srv.ListenAndServe(); err != nil {
              log.Printf("listenAndServe failed: %v", err)
          }
      }()
      fmt.Println("server started")
  
      // time.Sleep(1 * time.Second)
  
      // gracefully stop server
      d := time.Now().Add(60 * time.Second)
      ctx, cancel := context.WithDeadline(context.Background(), d)
      defer cancel()
      if err := srv.Shutdown(ctx); err != nil {
          fmt.Println(err)
      }
      fmt.Println("server stopped")
  
      &lt;-quit
  }
  </code></pre>
  
  <p>Simply run this program and access <a href="http://localhost:8080" rel="nofollow noreferrer">http://localhost:8080</a>. You will see it will keep serving requests even though we tried to shut it down.</p>
  
  <p>The output of the program should be:</p>
  
  <pre><code>:; go run main.go
  server started
  server stopped
  2017/07/22 16:17:11 serve failed: http: Server closed
  </code></pre>
  
  <p>instead it is:</p>
  
  <pre><code>:; go run main.go
  server started
  server stopped
  serving request
  serving request
  serving request
  </code></pre>