I recently encountered a strange problem in the project, that is, when using golang to debug the interface, the interface automatically closed after a period of time. This brings us a lot of inconvenience because we need to constantly restart the interface to continue debugging. In this article, I will share my solution.
First of all, I tracked the http package in the standard library in golang and found that essentially the http.Server type is the basis of all HTTP servers. I tried using this type to start my HTTP server and I solved the problem with deep debugging understanding. In the process, I discovered something interesting.
Before http.Server starts processing the request, it uses net.Listen to store a reference to the HTTP listener. Then, by instantiating the HTTP listener, you can start accepting new HTTP requests. This looks like the following:
l, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatal(err)
}
s := &http.Server{}
// Start processing the request
s.Serve(l)
After knowing this, I Turned to some third-party libraries to see their code implementations. We used some libraries such as gorilla mux and found that they do not use the above method to create HTTP services, but use the http.ListenAndServe function (I think this is the way many people use), as follows:
http .ListenAndServe(":8080", nil)
The second parameter is the route handler function we wrote (or any other type that implements the Handler interface).
http.ListenAndServe functions similarly to how we initialize an HTTP listener via net.Listen and start it using http.Server.Serve. However, it is simpler and can be done in one go.
When I replaced this, everything started working fine. The interface does not close automatically, I can set breakpoints in the code, reload or access the interface because it is always listening on the port. Actually, I think http.ListenAndServe should be used as the normal HTTP server startup method.
To summarize, if you encounter the problem of automatic shutdown of this interface when using golang, it is recommended to try using the http.ListenAndServe function to start the HTTP server. This may be an effective solution. Through an in-depth understanding of the golang standard library and third-party libraries, I hope it can help you better understand how golang works.
The above is the detailed content of golang debugging interface closed. For more information, please follow other related articles on the PHP Chinese website!