Go-http-HandlerFunc()函數

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

Keywords: HandlerFunc, ServeHTTP, NotFoundHandler

前言

在Go-HTTP中,已經介紹了HandlerFunc。為了查閱方便,單獨再拎出來講一講。

原始代碼

定義在server.go檔案中,如下。

// The HandlerFunc type is an adapter to allow the use of// ordinary functions as HTTP handlers. If f is a function// with the appropriate signature, HandlerFunc(f) is a// Handler that calls f.type HandlerFunc func(ResponseWriter, *Request)// ServeHTTP calls f(w, r).func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {    f(w, r)}

功能

HandlerFunc是一種資料類型,或者嚴格地講,是函數類型。不管怎麼說,HandlerFunc是一種type是無疑問的。而且,這個HandlerFunc實現了Handler介面的ServerHttp方法,所以HandlerFunc是Handler的具體類。

慣用法

習慣上,先定義自己的符合如下前面的函數:

func(ResponseWriter, *Request)

然後通過“類型轉換”,將該函數轉換成HandlerFunc類型,從而就變成了Handler對象。

樣本

在Go-HTTP一文,給出了相關的範例程式碼,再次拷貝過來(msgHandler):

package main import (    "fmt"    "log"    "net/http")func msgHandler(w http.ResponseWriter, r *http.Request) {    fmt.Fprint(w, "Hello, HandlerFunc!")}func main() {    mux := http.NewServeMux()    handler := http.HandlerFunc(msgHandler)    mux.Handle("/hello",  handler)    log.Println("Listening...")    http.ListenAndServe(":8080", mux)}

NotFoundHandler

server.go中的NotFoundHandler使用了同樣的手法:

// Error replies to the request with the specified error message and HTTP code.// It does not otherwise end the request; the caller should ensure no further// writes are done to w.// The error message should be plain text.func Error(w ResponseWriter, error string, code int) {    w.Header().Set("Content-Type", "text/plain; charset=utf-8")    w.Header().Set("X-Content-Type-Options", "nosniff")    w.WriteHeader(code)    fmt.Fprintln(w, error)}// NotFound replies to the request with an HTTP 404 not found error.func NotFound(w ResponseWriter, r *Request) { Error(w, "404 page not found", StatusNotFound) }// NotFoundHandler returns a simple request handler// that replies to each request with a ``404 page not found'' reply.func NotFoundHandler() Handler { return HandlerFunc(NotFound) }

這裡的NotFound()函數符合HandlerFunc類型的函數原型,所以通過HandlerFunc(NotFound)這個類型轉換,就產生了一個Handler對象。

正如server.go注釋所說的,NotFoundHandler這種都是helper形式的handler。——最開始接觸helper,是接觸ns3源碼的時候,ns3很多代碼就是xxxHelper這種命名方式。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.