使用net/http包的时候这个区别有点糊涂,所以查了一下 做一下总结
func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }
第二个参数是Handler这个接口, 这个接口有一个ServeHTTP()的方法
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
所以这个方法使用的时候需要自己去定义struct实现这个Handler接口。
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)
log.Fatal(http.ListenAndServe("localhost:9000", nil))
}
func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
DefaultServeMux.HandleFunc(pattern, handler)
}
这个第二个参数是一个方法,参数是ResponseWriter, 和 *Request 所以使用的时候需要传方法。
package main
import (
"net/http"
"log"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(r.URL.Path))
})
log.Fatal(http.ListenAndServe("localhost:9000", nil))
}
所以一般使用HandleFunc就可以了。