What is the HTTP request multiplexer?

I studied the golang, and I noticed that many people create servers using the http.NewServeMux() function, and I don’t quite understand what it does.

I read this:

In go ServeMux is an HTTP request multiplexer. It corresponds to the URL of each incoming request for a list of registered templates and calls the handler for the template that most closely matches the URL.

How is it other than just doing something like:

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

What is the purpose of using multiplexing?

+5
source share
1 answer

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 the only predefined http.ServeMux

 var DefaultServeMux = &defaultServeMux var defaultServeMux ServeMux 

As you can see the http.Handle calls to DefaultServeMux internally.

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

The purpose of http.NewServeMux() is to have your own http.Servermux instance for instances, for example when you need two http.ListenAndServe functions that listen on different ports with different routes.

+3
source

Source: https://habr.com/ru/post/1259438/


All Articles