Golang Tutorial: What's DefaultServeMux in net/http

craete a HTTPS Server use net/http and route handle function by DefaultServeMux, see code below:

package main

import (
	"net/http"
	"fmt"
	"log"
)

func hello(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "[%s]: hello!", r.Host)
}

func world(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "[%s]: world!", r.Host)
}

func main() {
	server := http.Server{
		Addr: "127.0.0.1:8080",
	}
	http.HandleFunc("/hello", hello)
	http.HandleFunc("/world", world)

	log.Fatal(server.ListenAndServe())
}

the http.HandleFunc is defined below:

package http

// HandleFunc registers the handler function for the given pattern
// in the DefaultServeMux.
// The documentation for ServeMux explains how patterns are matched.
func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
	DefaultServeMux.HandleFunc(pattern, handler)
}

DefaultServeMux is a ref var of &ServeMux

// DefaultServeMux is the default ServeMux used by Serve.
var DefaultServeMux = &defaultServeMux

var defaultServeMux ServeMux

And the method of HandleFunc is defined below:

package Server

// HandleFunc registers the handler function for the given pattern.
func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
	mux.Handle(pattern, HandlerFunc(handler))
}

// The HandlerFunc type is an adapter to allow the use of
// ordinary functions as HTTP handlers. If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// Handler that calls f.
type HandlerFunc func(ResponseWriter, *Request)

// ServeHTTP calls f(w, r).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
	f(w, r)
}

So we see, the method of HandleFunc convert arg of func(ResponseWriter, *Request) to a http Handler and passed to ServeMux.


(Note: My Code repository)

 Golang Tutorial: Create HTTPS Server use net/http RFC: TLS 1.0/1.1/1.2/1.3 

Comments