title: Golang net/http Server Handler Hot-Reload
body: <p>Is it possible to change the http Server's Handler struct field whilst the Server is running? I have a dynamic list of routes which can change throughout the lifetime of the server, but want to avoid any downtime.</p>
  
  <pre><code>package main
  
  import (
      "log"
      "net/http"
      "time"
  )
  
  func main() {
      // construct the handler for the first time
      handler, err := constructHandler()
      if err != nil {
          return nil, err
      }
  
      // create the server
      s := &amp;http.Server{
          Addr:    ":80",
          Handler: handler,
      }
  
      // start the server in on a separate goroutine.
      go func() {
          if err := s.ListenAndServe(); err != nil {
              log.Fatalf("unable to start http server: %v", err)
          }
      }()
  
      // recreate and hot-reload the handler every 30 seconds
      for range time.Tick(30 * time.Second) {
          handler, err = constructHandler()
          if err != nil {
              log.Printf("cannot reload: unable to construct handler: %v", err)
              continue
          }
  
          // only hot-reload the handler if there wasn't an error
          s.Handler = handler
      }
  }
  
  func constructHandler() (handler http.Handler, err error) {
      // handler gets created.
      // this could involve making calls to a database.
      // ...
      return handler, err
  }
  </code></pre>