Go-http-HandlerFunc()函数

    xiaoxiao2022-06-24  45

    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这种命名方式。

    转载请注明原文地址: https://ju.6miu.com/read-1123833.html

    最新回复(0)