What is an http request multiplexer?
Asked Answered
A

2

50

I've been studying golang and I noticed a lot of people create servers by using the http.NewServeMux() function and I don't really understand what it does.

I read this:

In go ServeMux is an HTTP request multiplexer. It matches the URL of each incoming request against a list of registered patterns and calls the handler for the pattern that most closely matches the URL.

How is that different than just doing something like:

http.ListenAndServe(addr, nil)
http.Handle("/home", home)
http.Handle("/login", login)

What is the purpose of using multiplexing?

Administer answered 8/11, 2016 at 2:34 Comment(3)
When you do that, you're using the multiplexer — namely, http.DefaultServeMux.Krahmer
ListenAndServe will use http.DefaultServeMux if you pass nil as the second parameterPreciosa
A request multiplexer is also called a request router. It routes incoming requests to a handler using some set of rules.Clothilde
C
33

From net/http GoDoc and Source.

ListenAndServe starts an HTTP server with a given address and handler. The handler is usually nil, which means to use DefaultServeMux. Handle and HandleFunc add handlers to DefaultServeMux

DefaultServeMux is just a predefined http.ServeMux

var DefaultServeMux = &defaultServeMux
var defaultServeMux ServeMux

As you can see http.Handle calls DefaultServeMux internally.

func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }

The purpose of http.NewServeMux() is to have your own instance of http.ServerMux for instances like when you require two http.ListenAndServe functions listening to different ports with different routes.

Countertenor answered 8/11, 2016 at 6:11 Comment(0)
H
8

the multiplexer in Golang is some things like multiplexer in hardware which multiply some inputs into some outputs

i gave you a simple exampe

type CustomMultiplexer struct {
}

the given multiplexer have to implement the ServeHTTP method to be registered int http to server inputs

func (mux CustomMultiplexer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path == "/" {
        SimpleRequestHandler(w, r)
        return
    }
    http.NotFound(w, r)
    return
}

my SimpleRequestHandler is a method as follow

func SimpleRequestHandler(w http.ResponseWriter, r *http.Request) {
    switch r.Method {
    case http.MethodGet:
        mySimpleGetRequestHandler(w, r)
        break
    default:
        http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
        break
    }
}

now i can use my CustomMultiplxere to do multiplexing between incoming requested

func main() {
    customServer := CustomServer{}
    err := http.ListenAndServe(":9001", &customServer)
    if err != nil {
        panic(err)
    }
}

the http.HandleFunc method works as my given simple multiplexer.

Hypermetropia answered 5/2, 2020 at 18:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.