Copied
Please follow the site license
报告
章节_文章 // 现场报告

文章编号: RL-GO的接口型函数

2026.06.18

Go 的接口型函数

Chavy
Chavy
#Go#Interface#Design Pattern
分析

摘要:探讨 Go 语言中经典的接口型函数设计模式,分析其工作原理、使用场景与优雅之处。

在 net/http 包中,HandlerFunc 为函数,实现了 Handler 接口。

PRTCL // GO
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
type HandlerFunc func(ResponseWriter, *Request)
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
f(w, r)
}

这样实现后,只要你的函数签名为:

PRTCL // GO
func (ResponseWriter, *Request)

拥有http.HandlerFunc()一致的函数签名,就可以将该函数进行类型转换,转换为 http.HandlerFunc 函数类型。且http.HandlerFunc函数类型实现了Handler 接口,则你命名的函数转换后也相当于实现了Handler接口。

我们可以 <font style="color:rgb(36, 41, 46);">http.Handle</font> 来映射请求路径和处理函数,Handle 的定义如下:

PRTCL // GO
func Handle(pattern string, handler Handler)

第二个参数是即接口类型 Handler,我们可以这么用。

PRTCL // GO
func home(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("hello, index page"))
}
func main() {
http.Handle("/home", http.HandlerFunc(home))
_ = http.ListenAndServe("localhost:8000", nil)
}

通常,我们还会使用另外一个函数 <font style="color:rgb(36, 41, 46);">http.HandleFunc</font>,HandleFunc 的定义如下:

PRTCL // GO
func HandleFunc(pattern string, handler func(ResponseWriter, *Request))

第二个参数是一个普通的函数类型,那可以直接将 home 传递给 HandleFunc:

PRTCL // GO
func main() {
http.HandleFunc("/home", home)
_ = http.ListenAndServe("localhost:8000", nil)
}

那如果我们看过 HandleFunc 的内部实现的话,就会知道两种写法是完全等价的,内部将第二种写法转换为了第一种写法。

PRTCL // GO
func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
if handler == nil {
panic("http: nil handler")
}
mux.Handle(pattern, HandlerFunc(handler))
}
R P
莱茵实验室先锋部
认证_已验证: 2026.06.18
// 文章结束

Subscribe

Subscribe via RSS to receive notifications when new posts are published.

Follow
Classified
章节_06
协议编号: CC-BY-NC-SA-4.0

Go 的接口型函数

作者:CHONGXI发布日期:2026.06.18

基于 CC BY-NC-SA 4.0

05 // 传输日志记录

© 2025-2026 Lonetrail
Powered by Astro & Lonetrail 非协作实体 // 协议_V.4.21