比第一個(gè)版本更加底層。通過ServeMux來控制路由的訪問,ServeMux本質(zhì)上只是一個(gè)路由管理器,而它本身也實(shí)現(xiàn)了Handler接口的ServeHTTP方法
server2.go?
package main
import (
????????"io"
????????"net/http"
????????"log"
)
func main () {
????????mux := http.NewServeMux()
????????mux.Handle("/", &myHandler{})????
????????mux.HandleFunc("/hello", sayTwo)
????????err := http.ListenAndServe(":6066", mux)
????????if err != nil {
????????????log.Fatal(err)
????????}
}
// 自己實(shí)現(xiàn)一個(gè)handler,注冊(cè)到mux中,然后再實(shí)現(xiàn)一個(gè)路由的注冊(cè)
type myHandlerstruct {}
// 只需實(shí)現(xiàn)一個(gè)方法
func (*myHandler) ServeHTTP (w http.ResponseWriter, r *http.Request)? {
????????io.WriteString(w, "URL: " + r.URL.String())
}
func sayTwo (w http.ResponseWriter, r *http.Request) {
????????io.WriteString(w, "this is version 2")
}
go run server2.go

