前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >go源码分析(二) 使用go http包开发web时遇到的坑之重复注册Handle路由

go源码分析(二) 使用go http包开发web时遇到的坑之重复注册Handle路由

作者头像
杜争斌
发布2022-04-27 19:20:16
4300
发布2022-04-27 19:20:16
举报
文章被收录于专栏:我的博文我的博文

我们使用Handle注册http时

如果添加两行,即重复注册函数。

http.HandleFunc("/",index)

http.HandleFunc("/",index)

系统会直接报错

代码语言:javascript
复制
goroutine 26 [running]:
net/http.(*ServeMux).Handle(0xc9eca0, 0x8b61dd, 0x1, 0x8fbc40, 0x8d1658)
	/usr/local/go/src/net/http/server.go:2353 +0x239
net/http.(*ServeMux).HandleFunc(0xc9eca0, 0x8b61dd, 0x1, 0x8d1658)
	/usr/local/go/src/net/http/server.go:2368 +0x55
net/http.HandleFunc(0x8b61dd, 0x1, 0x8d1658)
	/usr/local/go/src/net/http/server.go:2380 +0x4b
_/mnt/hgfs/github/jiuyinzhenjing/0002/gosrc/gopl_learn/022_go_web/server.Server()
	/mnt/hgfs/github/jiuyinzhenjing/0002/gosrc/gopl_learn/022_go_web/server/server.go:49 +0x594
created by main.main
	/mnt/hgfs/github/jiuyinzhenjing/0002/gosrc/gopl_learn/022_go_web/main.go:23 +0x50

 在/usr/local/go/src/net/http/server.go中发生了恐慌,

我们查看代码如下,当发现已经注册的函数已经存在时,直接发生panic(12行),提示多次注册函数。这样的做法容错性不高。

代码语言:javascript
复制
func (mux *ServeMux) Handle(pattern string, handler Handler) {
	mux.mu.Lock()
	defer mux.mu.Unlock()

	if pattern == "" {
		panic("http: invalid pattern")
	}
	if handler == nil {
		panic("http: nil handler")
	}
	if _, exist := mux.m[pattern]; exist {
		panic("http: multiple registrations for " + pattern)
	}

	if mux.m == nil {
		mux.m = make(map[string]muxEntry)
	}
	e := muxEntry{h: handler, pattern: pattern}
	mux.m[pattern] = e
	if pattern[len(pattern)-1] == '/' {
		mux.es = appendSorted(mux.es, e)
	}

	if pattern[0] != '/' {
		mux.hosts = true
	}
}

 这个问题对我的影响

当我需要动态加载模块时,已有的模块可能发生重复加载的情况,会发生重复加载的情况

把(12行)第三个if也就是多次注册函数的panic修改为return,直接退出,即可解决该问题

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-11-28,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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