知识卡片

结构图卡 · 1373.d.1

HandlerFunc适配器

理解等级:中级

http.Handler 要求 ServeHTTP 方法。HandlerFunc 是带有该方法的命名函数类型,因方法集合满足 Handler,属于隐式实现而非继承。签名匹配的普通函数可转换为 HandlerFunc,其 ServeHTTP 再调用原函数;http.Handle 因而能按统一接口使用函数处理器。

结构图:

类图(ArgServer 是原文的函数示例,不是类;虚线空心三角表示隐式实现):

classDiagram
    direction LR
    class Handler {
        <<interface>>
        +ServeHTTP(ResponseWriter, *Request)
    }
    class HandlerFunc {
        <<function type>>
        +ServeHTTP(w ResponseWriter, req *Request)
    }
    class ArgServer["ArgServer(函数,非类型)"]
    ArgServer ..> HandlerFunc : 签名匹配时转换
    HandlerFunc ..|> Handler : 隐式实现
    HandlerFunc ..> ArgServer : ServeHTTP 调用原函数

构造与调用结构图:

flowchart LR
    A[普通处理函数] -->|转换类型| B[HandlerFunc 值]
    B -->|具备 ServeHTTP| C[Handler 接口]
    C --> D[HTTP 服务调用]
    D -->|调用 ServeHTTP| B
    B -->|调用原函数| A
这张卡片看不懂?

已有反馈 · 0 / 10 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《Effective Go中文版》第11章《接口和其它类型》(源文件:`_epub-src/OEBPS/接口和其它类型.md.html`) - 结论依据:原文展示 `Handler` 的方法要求、`HandlerFunc` 的函数类型与 `ServeHTTP` 方法,并以 `http.Handle("/args", http.HandlerFunc(ArgServer))` 说明签名匹配的函数如何转换为满足接口的处理器。 - 原始内容:The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers.……type HandlerFunc func(ResponseWriter, *Request)……func (f HandlerFunc) ServeHTTP(w ResponseWriter, req *Request) { f(w, req) }