Handle Unregistration in net/http
HTTP handlers in net/http can be dynamically registered and unregistered to provide flexibility in handling requests. To unregister a handler, a custom ServerMux can be created.
Implementing a Custom ServerMux
Copy the code for ServerMux from the Go source code (GOROOT/src/pkg/net/http/server.go, lines 837-939). Add a Deregister method to the custom ServerMux to remove handlers from the pattern-to-Handler mapping:
<code class="go">func (mux *MyMux) Deregister(pattern string) error { mux.mu.Lock() defer mux.mu.Unlock() del(mux.m, pattern) return nil }</code>
Usage
Create an instance of the custom ServerMux and handle the "/create" route as usual:
<code class="go">mux := newMux() mux.Handle("/create", &factory)</code>
Set the custom ServerMux as the Handler for an HTTP server:
<code class="go">srv := &http.Server { Addr: localhost:8080 Handler: mux, }</code>
Unregistration
To unregister a handler, simply call the Deregister method on the ServerMux:
<code class="go">mux.Deregister("/123/*")</code>
This will modify the routing behavior of the server, and subsequent requests to "/123/*" will no longer be handled by the previously registered handler.
Safe Modifications
Modifying the ServerMux by calling deregister() from another goroutine is safe and will update the routing logic for the server.
The above is the detailed content of How to Deregister HTTP Handlers in Go's net/http?. For more information, please follow other related articles on the PHP Chinese website!