Home >Backend Development >Golang >How to Unregister Handlers in Go's `net/http` Package?

How to Unregister Handlers in Go's `net/http` Package?

DDD
DDDOriginal
2024-11-05 15:08:02494browse

How to Unregister Handlers in Go's `net/http` Package?

Unregistering Handlers in net/http

In net/http, handlers can be registered and unregistered at runtime. This allows for dynamic configuration of web servers.

Registering Handlers

The following code demonstrates how to register a handler at runtime using a HandlerFactory:

<code class="go">package main

import (
    "fmt"
    "net/http"
)

type MyHandler struct {
    id int
}

func (hf *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, r.URL.Path)
}

// Creates MyHandler instances and registers them as handlers at runtime
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, &amp;handler)
}

func main() {
    factory := HandlerFactory{0}
    http.Handle("/create", &amp;factory)
    http.ListenAndServe("localhost:8080", nil)
}</code>

Unregistering Handlers

To unregister a handler, a custom ServerMux can be created and used. This custom ServerMux includes a Deregister method that removes a pattern-to-handler mapping from the map:

<code class="go">// TODO: check if registered and return error if not.
// TODO: possibly remove the automatic permanent link between /dir and /dir/.
func (mux *MyMux) Deregister(pattern string) error {
    mux.mu.Lock()
    defer mux.mu.Unlock()
    del(mux.m, pattern)
    return nil
}</code>

Using this custom ServerMux:

<code class="go">mux := newMux()
mux.Handle("/create", &amp;factory)

srv := &amp;http.Server {
    Addr: localhost:8080
    Handler: mux,
}
srv.ListenAndServe()</code>

Deregistering handlers from this custom ServerMux can be done safely from another goroutine, without affecting the routing of messages by ListenAndServe().

The above is the detailed content of How to Unregister Handlers in Go's `net/http` Package?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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