• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Go接口转换的一个例子

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

今天将Go 的websocket集成到已有的http中时也遇到以下一个问题:其中主要是接口类型转换

转载自[http://www.cnblogs.com/ghj1976/archive/2013/04/23/3037914.html]


 我们用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集成到已有的http

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)


type websocket.Handler func(*websocket.Conn)

Handler is a simple interface to a WebSocket browser client. It checks if Origin header is valid URL by default. You might want to verify websocket.Conn.Config().Origin in the func. If you use Server instead of Handler, you could call websocket.Origin and check the origin in your Handshake func. So, if you want to accept non-browser client, which doesn't send Origin header, you could use Server . that doesn't check origin in its Handshake.

  • method

    (websocket.Handler).ServeHTTP(w net/http.ResponseWriter, req *net/http.Request)

ServeHTTP implements the http.Handler interface for a WebSocket

通过以前的信息可以看出websocket.Handler实现了http.Handler接口,从而实现了接口类型的转换。

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
GO语言调试利器dlv快速上手发布时间:2022-07-10
下一篇:
go-zero微服务实战系列(一、开篇)发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap