Go语言的“http.Handle”和“http.HandleFunc”

Go语言中http package包含HandleHandleFunc两个函数:

func Handle

func Handle(pattern string, handler Handler)
Handle registers the handler for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

func HandleFunc

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

Handle函数的handler参数是个interface

type Handler interface {
        ServeHTTP(ResponseWriter, *Request)
}

HandleFunchandler参数就是一个原型为func(ResponseWriter, *Request)的函数。

参考下例(使用Handle):

package main
import (
    "net/http"
    "log"
)

type httpServer struct {
}

func (server httpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte(r.URL.Path))
}

func main() {
    var server httpServer
    http.Handle("/", server)
    log.Fatal(http.ListenAndServe("localhost:9000", nil))
}

使用HandleFunc

package main
import (
    "net/http"
    "log"
)

func main() {
    http.HandleFunc("/", func (w http.ResponseWriter, r *http.Request){
        w.Write([]byte(r.URL.Path))
    })
    log.Fatal(http.ListenAndServe("localhost:9000", nil))
}

根据The Go Programming Language

A handler pattern that ends with a slash matches any URL that has the pattern as a prefix. Behind the scenes, the server runs the handler for each incoming request in a separate goroutine so that it can serve multiple requests simultaneously.

因此,如果http.Handlehttp.HandleFunc所指定的handle pattern是“/”,则匹配所有的pattern;而“/foo/”则会匹配所有“/foo/*”。

发表评论

邮箱地址不会被公开。 必填项已用*标注

This site uses Akismet to reduce spam. Learn how your comment data is processed.