The Server from the net/http package provides the method to gracefully shutdown the connection. The preceding code starts the HTTP server in a separate goroutine and keeps the reference to the Server struct in a variable.
By calling the Shutdown method, the Server starts refusing new connections and closes opened listeners and idle connections. Then it waits indefinitely for the already pending connections, till these become idle. After all the connections are closed, the server shuts down. Note that the Shutdown method consumes the Context. If the provided Context expires prior to the shutdown, then the error from Context is returned and the Shutdown does not block anymore.