Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

go - Difference between http and default servemux?

What's the difference between this:

func main() {

  http.HandleFunc("/page2", Page2)
  http.HandleFunc("/", Index)
  http.ListenAndServe(":3000", nil)
}

And using the golang serve mux

func main() {
  mux := http.NewServeMux()

  mux.HandleFunc("/page2", Page2)
  mux.HandleFunc("/", Index)
  http.ListenAndServe(":3000", mux)
}
question from:https://stackoverflow.com/questions/36921190/difference-between-http-and-default-servemux

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The first program uses the default serve mux. It's identical to the more verbose:

func main() {
  http.DefaultServeMux.HandleFunc("/page2", Page2)
  http.DefaultServeMux.HandleFunc("/", Index)
  http.ListenAndServe(":3000", http.DefaultServeMux)
}

There's one important difference between the two programs: The first program does not have complete control over the handlers used in the program. There are packages that automatically register with the default serve mux from init() functions (example). If the program imports one of these packages directly or indirectly, the handlers registered by these handlers will be active in the first program.

The second program has complete control over the handlers used with the server. Any handlers registered with the default serve mux are ignored.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...