前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >go http http.Handle 和 http.HandleFunc 区别

go http http.Handle 和 http.HandleFunc 区别

作者头像
solate
发布2019-07-22 17:57:03
6.1K0
发布2019-07-22 17:57:03
举报
文章被收录于专栏:solate 杂货铺solate 杂货铺

使用net/http包的时候这个区别有点糊涂,所以查了一下 做一下总结

区别

http.Handle

代码语言:javascript
复制
func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }

第二个参数是Handler这个接口, 这个接口有一个ServeHTTP()的方法

代码语言:javascript
复制
type Handler interface {
	ServeHTTP(ResponseWriter, *Request)
}

所以这个方法使用的时候需要自己去定义struct实现这个Handler接口。

代码语言:javascript
复制
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))
}

http.HandleFunc

代码语言:javascript
复制
func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
	DefaultServeMux.HandleFunc(pattern, handler)
}

这个第二个参数是一个方法,参数是ResponseWriter, 和 *Request 所以使用的时候需要传方法。

代码语言:javascript
复制
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就可以了。

参考

Go语言的“http.Handle”和“http.HandleFunc”

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 区别
    • http.Handle
      • http.HandleFunc
      • 参考
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档