Go-http-HandlerFunc()函数

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值