zoukankan      html  css  js  c++  java
  • Golang的interface一个例子

    我们用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) {

  • 相关阅读:
    tomcat bug之部署应用的时候经常会发上startup failed due to previous errors
    maven编译项目理解
    MyReport报表引擎2.6.5.0新功能
    PHP入门-摘要表格处理问题
    EnumMap源代码阅读器
    MySQL几种方法的数据库备份
    工作日志2014-08-19
    Linux通过网卡驱动程序和版本号的信息
    JS于,子类调用父类的函数
    hdu 5007 水 弦
  • 原文地址:https://www.cnblogs.com/ghj1976/p/3037914.html
Copyright © 2011-2022 走看看