go语言中的http.Handle和http.HandleFunc

go语言中的http.Handle和http.HandleFunc
go的http库中Handle和HandleFunc的第一个参数都是pattern,即请求路径,区别在于第二参数。

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

Handle的第二个参数是接口类型,该接口只有一个方法:

type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}

因此我们需要自定义结构体和ServeHTTP方法以实现该接口。例如:

package main

import (
    "net/http"
    "log"
)

type httpServer struct {
}

func (server httpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte(r.URL.Path))
}

func main() {
    var server httpServer
    http.Handle("/", server)
    http.ListenAndServe("localhost:9000", nil)
}

HandleFunc
HandleFunc的第二个参数是函数类型func(ResponseWriter, *Request)。

func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
    DefaultServeMux.HandleFunc(pattern, handler)
}

因此在使用时需要引入相应类型的函数,例如:

package main

import (
    "net/http"
    "log"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte(r.URL.Path))
    })
    http.ListenAndServe("localhost:9000", nil)
}

总结
由上面的分析和例子可以看出,本质上两个函数是一样的,只是Handle多定义了一层接口类型,该接口的方法其实跟HandleFunc中的函数参数类型是一样的。

https://blog.csdn.net/weixin_43889827/article/details/120534343

posted @ 2015-05-17 16:10  南哥的天下  阅读(592)  评论(0编辑  收藏  举报