Unregistering a Handler in net/http
In net/http, handlers can be dynamically registered to specific URL patterns using the http.Handle function. However, the default multiplexer does not provide a mechanism for unregistering handlers.
One approach to unregister a handler is to create a custom multiplexer that extends the standard http.ServeMux type. This custom multiplexer can include a method for deregistering handlers. For instance, the following code defines a custom multiplexer that adds a Deregister method:
type MyMux struct {
*http.ServeMux
mu sync.Mutex // Guards the m map
m map[string]http.Handler
}
func (mux *MyMux) Deregister(pattern string) error {
mux.mu.Lock()
defer mux.mu.Unlock()
if _, ok := mux.m[pattern]; !ok {
return errors.New("handler not registered")
}
delete(mux.m, pattern)
return nil
}
Once the custom multiplexer is defined, it can be used to handle requests. For instance:
mux := new(MyMux)
mux.Handle("/create", &factory)
srv := &http.Server{
Addr: "localhost:8080",
Handler: mux,
}
srv.ListenAndServe()
Calling the Deregister method on the custom multiplexer will stop the corresponding handler from servicing requests. Note that the handler must be registered using the same custom multiplexer instance for the deregistration to be effective.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3