go http http.Handle 和 http.HandleFunc 区别

本文详细对比了Go语言中http.Handle与http.HandleFunc两个函数的不同之处,前者需要自定义实现Handler接口,而后者则直接接受处理函数。通过具体代码示例展示了这两种方式的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

区别

http.Handle

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))
}

http.HandleFunc

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就可以了。

参考

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

转载于:https://my.oschina.net/solate/blog/859771

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值