Go-http-HandlerFunc()函数

u013344915 · · 2472 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

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


有疑问加站长微信联系(非本文作者)

本文来自:CSDN博客

感谢作者:u013344915

查看原文:Go-http-HandlerFunc()函数

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2472 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传