Home > Backend Development > Golang > How to Deregister HTTP Handlers in Go's net/http?

How to Deregister HTTP Handlers in Go's net/http?

Mary-Kate Olsen
Release: 2024-11-05 17:01:02
Original
901 people have browsed it

How to Deregister HTTP Handlers in Go's net/http?

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>
Copy after login

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>
Copy after login

Set the custom ServerMux as the Handler for an HTTP server:

<code class="go">srv := &http.Server {
    Addr: localhost:8080
    Handler: mux,
}</code>
Copy after login

Unregistration

To unregister a handler, simply call the Deregister method on the ServerMux:

<code class="go">mux.Deregister("/123/*")</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template