随笔 - 934, 文章 - 0, 评论 - 249, 阅读 - 345万

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

Golang的interface一个例子

Posted on   蝈蝈俊  阅读(1852)  评论(0编辑  收藏  举报

我们用Golang做网站时,必然会有这样的代码:

http.Handle("/", http.FileServer(http.Dir(".")))

注意这里的 http.Handle( 函数的第二个参数,Golang的源码中这个函数的描述如下:

// Handle registers the handler for the given pattern

// in the DefaultServeMux.

// The documentation for ServeMux explains how patterns are matched.

func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }

 

其中第二个参数是一个 interface,必须实现ServeHTTP(ResponseWriter, *Request)方法

// Objects implementing the Handler interface can be

// registered to serve a particular path or subtree

// in the HTTP server.

//

// ServeHTTP should write reply headers and data to the ResponseWriter

// and then return.  Returning signals that the request is finished

// and that the HTTP server can move on to the next request on

// the connection.

type Handler interface {

    ServeHTTP(ResponseWriter, *Request)

}

 

如果我们用WebSocket时,又会发现, 我们给http.Handle( 传递的是 websocket.Handler(。

http.Handle("/socket", websocket.Handler(Echo))

 

websocket.Handler 又是另外一个接口,如下

// Handler is an interface to a WebSocket.

type Handler func(*Conn)

 

这里为啥会出现接口更换了? 其实 再往下看可以看到 websocket.Handler 接口多一个公共的方法:ServeHTTP, 即接口 websocket.Handler 实现了 http 的 Handler 接口。

 

// ServeHTTP implements the http.Handler interface for a Web Socket

func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {

 

 

这里的interface有了其他语言类的一些特征,比较有趣。


// Handler is an interface to a WebSocket.type Handler func(*Conn)
// ServeHTTP implements the http.Handler interface for a Web Socketfunc (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示