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

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

Go語言中http package包含HandleHandleFunc兩個函數:

func Handlefunc 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 HandleFuncfunc 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 mainimport (    "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 mainimport (    "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/*”。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.