go源码分析(二) 使用go http包开发web时遇到的坑之重复注册Handle路由
我们使用Handle注册http时
如果添加两行,即重复注册函数。
http.HandleFunc("/",index)
http.HandleFunc("/",index)
系统会直接报错
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行),提示多次注册函数。这样的做法容错性不高。
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,直接退出,即可解决该问题
一法通,万法通,诸般深奥的学问到了极处,本是殊途同归。
浙公网安备 33010602011771号