上一篇里討論了 go 官方庫里提供的 http 服務(wù)框架,使用者需要關(guān)心的是 Server 的 handler 域。當 Server 調(diào)用 Serve 函數(shù)時 Server.Handler 為 nil,則默認使用 http.DefaultServeMux 作為 handler。
DefaultServeMux
來看一下它的定義和描述:
// 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.
簡單的說,它就是一個路由分發(fā)器。
路由注冊
type ServeMux struct {
mu sync.RWMutex
m map[string]muxEntry
//路由規(guī)則,一個string對應(yīng)一個mux實例對象,map的key就是注冊的路由表達式(string類型的)
hosts bool // whether any patterns contain hostnames
}
var defaultServeMux ServeMux
var DefaultServeMux = &defaultServeMux
type muxEntry struct { // 代表著一個 路由-處理函數(shù) 組合
explicit bool //表示 patern 是否已經(jīng)被明確注冊過了
h Handler
pattern string //路由表達式
}
之前提到過,Server.Handler 需要有路由功能,并且可以執(zhí)行路由對應(yīng)的處理函數(shù)。當注冊路由時,調(diào)用mux.Handle:
func (mux *ServeMux) Handle(pattern string, handler Handler) {
mux.mu.Lock()
defer mux.mu.Unlock()
if pattern == "" {
panic("http: invalid pattern " + pattern)
}
if handler == nil {
panic("http: nil handler")
}
if mux.m[pattern].explicit {
panic("http: multiple registrations for " + pattern)
}
if mux.m == nil {
mux.m = make(map[string]muxEntry)
}
mux.m[pattern] = muxEntry{explicit: true, h: handler, pattern: pattern}
if pattern[0] != '/' {
mux.hosts = true
}
// 以下是很有用的功能:當pattern == “/tree/”時,
// 會插入一條永久的重定向到“/tree”,注意最后的斜杠。
// 當然前提是在這之前沒有“/tree”這條路由
n := len(pattern)
if n > 0 && pattern[n-1] == '/' && !mux.m[pattern[0:n-1]].explicit {
//如果包含host,
path := pattern
if pattern[0] != '/' {
// In pattern, at least the last character is a '/', so
// strings.Index can't be -1.
path = pattern[strings.Index(pattern, "/"):]
}
url := &url.URL{Path: path}
mux.m[pattern[0:n-1]] = muxEntry{h: RedirectHandler(url.String(), StatusMovedPermanently), pattern: pattern}
}
}
代碼挺多,其實主要就做了一件事,向DefaultServeMux的map[string]muxEntry中增加對應(yīng)的路由規(guī)則和handler。注意這里每條路由并沒有包含我們常說的 GET、POST 等等區(qū)別,主要有兩個原因:一是為了簡潔,很多開發(fā)者偏好不同的處理方法,官方庫只提供最基本的功能;二是不直接和請求方法綁定起來便于寫 RESTful API。
但是這里還要注意路徑結(jié)尾的/,這時候該路徑為一個子樹,如果能完全匹配到其子路由,那么也能匹配到這個子樹,不過路由越長,優(yōu)先級越大;如果不能完全匹配到其子路由,會匹配到這個子樹的路由。比如有一個根路由/、/example/和 /example/1,那么訪問/example/2時,會匹配到/example/,訪問/nothing會匹配到/。
處理路由請求
注冊好路由,并且沒有使用別的 handler 時,DefaultServerMux 的 ServeHTTP 就會在接收到 request 時被調(diào)用。
func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request) {
handler := sh.srv.Handler
if handler == nil {
handler = DefaultServeMux
}
if req.RequestURI == "*" && req.Method == "OPTIONS" {
handler = globalOptionsHandler{}
}
handler.ServeHTTP(rw, req)
}
ServeHTTP 主要從之前注冊好的路由表中獲取對應(yīng)的 handler:
func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
...
h, _ := mux.Handler(r) // 匹配和 request 最接近的路由,拿到對應(yīng)的 handler
h.ServeHTTP(w, r)
}
func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) {
...
host := stripHostPort(r.Host)
path := cleanPath(r.URL.Path)
if path != r.URL.Path {
_, pattern = mux.handler(host, path)
url := *r.URL
url.Path = path
return RedirectHandler(url.String(), StatusMovedPermanently), pattern
//注意這里的重定向 handler
}
return mux.handler(host, r.URL.Path)
}
func (mux *ServeMux) handler(host, path string) (h Handler, pattern string) {
mux.mu.RLock()
defer mux.mu.RUnlock()
// Host-specific pattern takes precedence over generic ones
if mux.hosts {
h, pattern = mux.match(host + path)
}
if h == nil {
h, pattern = mux.match(path) // match 做的是字符串匹配的工作
}
if h == nil {
h, pattern = NotFoundHandler(), ""
}
return
}
在沒有找到匹配的路由時,返回 NotFoundHandler, 默認只是寫入 404 not found,但通常我們會自定義它,然后返回一個專門的好看的 404 頁面。
如果需要重定向,則會通過返回的 redirectHandler 調(diào)用 Redirect:
func Redirect(w ResponseWriter, r *Request, url string, code int) {
if u, err := parseURL(url); err == nil {
// If url was relative, make absolute by
// combining with request path.
// The browser would probably do this for us,
// but doing it ourselves is more reliable.
// NOTE(rsc): RFC 2616 says that the Location
// line must be an absolute URI, like
// "http://www.google.com/redirect/",
// not a path like "/redirect/".
// Unfortunately, we don't know what to
// put in the host name section to get the
// client to connect to us again, so we can't
// know the right absolute URI to send back.
// Because of this problem, no one pays attention
// to the RFC; they all send back just a new path.
// So do we.
if u.Scheme == "" && u.Host == "" {
oldpath := r.URL.Path
if oldpath == "" { // should not happen, but avoid a crash if it does
oldpath = "/"
}
// no leading http://server
if url == "" || url[0] != '/' {
// make relative path absolute
olddir, _ := path.Split(oldpath)
url = olddir + url
}
var query string
if i := strings.Index(url, "?"); i != -1 {
url, query = url[:i], url[i:]
}
// clean up but preserve trailing slash
trailing := strings.HasSuffix(url, "/")
url = path.Clean(url)
if trailing && !strings.HasSuffix(url, "/") {
url += "/"
}
url += query
}
}
w.Header().Set("Location", hexEscapeNonASCII(url))
w.WriteHeader(code)
// RFC 2616 recommends that a short note "SHOULD" be included in the
// response because older user agents may not understand 301/307.
// Shouldn't send the response for POST or HEAD; that leaves GET.
if r.Method == "GET" {
note := "<a href=\"" + htmlEscape(url) + "\">" + statusText[code] + "</a>.\n"
fmt.Fprintln(w, note)
}
}
可以看到,DefaultServerMux 只有一個最基本的路由功能,是一個最簡單的 HTTP 服務(wù)框架??墒沁@通常不能滿足我們的需求,于是我們可以根據(jù)我們自己的需要自定義一個簡單通用的 HTTP Server 框架。