In net/http, handling runtime-registered handlers requires a custom approach. While the HTTP server provides a mechanism for registering handlers, it lacks the ability to unregister them dynamically.
To create and register handlers dynamically, you can use a custom HandlerFactory. This can be designed to generate new handlers with unique IDs and register them using http.Handle. For example, a "/create" handler could generate MyHandler instances with increasing IDs and map them to specific URL patterns.
<code class="go">type HandlerFactory struct { handler_id int } func (hf *HandlerFactory) ServeHTTP(w http.ResponseWriter, r *http.Request) { hf.handler_id++ handler := MyHandler{hf.handler_id} handle := fmt.Sprintf("/%d/", hf.handler_id) http.Handle(handle, &handler) }</code>
To provide unregistered handlers, you'll need to create a custom ServerMux that extends the original ServeMux and includes a deregistration method.
<code class="go">type MyMux struct { http.ServeMux mu sync.Mutex } func (mux *MyMux) Deregister(pattern string) error { mux.mu.Lock() defer mux.mu.Unlock() del(mux.m, pattern) // Handle additional error checking or setup here }</code>
To use this custom ServerMux, you can instantiate a new one and wrap it inside an HTTP server using http.Handler:
<code class="go">mux := new(MyMux) mux.Handle("/create", &factory) srv := &http.Server{ Addr: "localhost:8080", Handler: mux, } go srv.ListenAndServe() // Deregister handlers as needed mux.Deregister("/123/*")</code>
This approach allows you to dynamically register and unregister handlers, providing the flexibility needed for handling runtime-generated URL patterns.
The above is the detailed content of How can you dynamically register and unregister HTTP handlers in Go's net/http package?. For more information, please follow other related articles on the PHP Chinese website!