You are developing a command-line bot that interacts with the Instagram API using OAuth, which is not optimized for command-line applications. To overcome this, you have set up a local HTTP server as the redirect URI for authorization. After the user authorizes the application and is redirected to the server, you'd like to shut down the server once the access token has been displayed.
You have encountered an issue when implementing the shutdown mechanism. Specifically, calling srv.Shutdown(nil) in the request handler (showTokenToUser) leads to an error:
2017/11/23 16:02:03 Httpserver: ListenAndServe() error: http: Server closed 2017/11/23 16:02:03 http: panic serving [::1]:61793: runtime error: invalid memory address or nil pointer dereference
The issue arises because you are calling srv.Shutdown(nil) multiple times:
Calling srv.Shutdown while the server is still listening for connections leads to a race condition. The ListenAndServe() goroutine attempts to close the open listeners and idle connections, but it's interrupted by the subsequent call to Shutdown in the handler closure. This state inconsistency triggers the panic.
To resolve this issue, you can use one of two methods:
1. Use context.WithCancel:
In this approach, you create a context.Context with a cancel function. The context is passed to the ListenAndServe goroutine and the showTokenToUser handler function. Inside the handler, when the access token has been displayed to the user, you call the cancel function to terminate the context. The ListenAndServe goroutine will gracefully shut down the server when the context is canceled.
2. Use the same Context:
Instead of calling context.WithCancel, you can pass the same context.Context to the ListenAndServe goroutine and the handler function. When the access token is displayed, you call cancel() on the context, which will trigger the shutdown of both the handler and the ListenAndServe goroutine.
After implementing either approach, remember to wait for the srv.Shutdown function to complete before exiting the program.
The above is the detailed content of How to Gracefully Shut Down an HTTP Server After Returning a Response?. For more information, please follow other related articles on the PHP Chinese website!