英文:
How to pass net/http to other package
问题
我使用以下代码片段来创建一个HTTP服务器。
在主包中:
http.HandleFunc("/aa", aahandler)
http.Handle("/echo", websocket.Handler(bbhandler.Wshandle))
...
http.ListenAndServe()
bbhandler 是我自定义的包。
以上代码可以正常工作。
现在我想在 bbhandler 中添加一个 Register 函数。
Register() {
    http.Handle("/echo", websocket.Handler(Wshandle))
    ...
}
然后,主包中的代码将变为:
http.HandleFunc("/aa", aahandler)
bbhandler.Register()
...
http.ListenAndServe()
但是上述代码似乎不起作用,因为主程序不会处理 /echo,看起来 bbhandler.Register 没有将 /echo 添加到主程序的 http 中。那么我该如何将主程序的 http 传递给 bbhandler 并添加 /echo 处理函数呢?
英文:
I use below code snippet for http server.
in main package:
http.HandleFunc("/aa", aahandler)
http.Handle("/echo", websocket.Handler(bbhandler.Wshandle))  
...
http.ListenAndServe()
the bbhandler is self-defined package.
Above code works.
Now I want to add a function Register in bbhandler.
Register() {
    http.Handle("/echo", websocket.Handler(Wshandle))  
    ... 
}
and main package code snippet will become as:
http.HandleFunc("/aa", aahandler)
bbhandler.Register()
...
http.ListenAndServe()
But above code seems not work, as main program will not handle /echo, it seems bbhandler.Register do not add /echo into main's http, So how can I pass main's http into bbhandler and add /echo handler function.
答案1
得分: 1
这应该可以工作。两个调用都使用了http.DefaultServeMux,它是一个包级别的变量,对于两个导入来说是同一个对象。
话虽如此,如果你将一个*http.ServeMux传递给Register,让调用者对处理程序的添加位置有控制,那将是更好的设计:
Register(mux *http.ServeMux) {
    mux.Handle("/echo", websocket.Handler(Wshandle))  
    ... 
}
在main函数中:
http.HandleFunc("/aa", aahandler)
bbhandler.Register(http.DefaultServeMux)
...
http.ListenAndServe()
英文:
This should work. Both invocations use http.DefaultServeMux, which is a package-level variable that is the very same object for both imports.
That said, it would be better design if you passed a *http.ServeMux into Register so the caller has control over where the handler gets added:
Register(mux *http.ServeMux) {
    mux.Handle("/echo", websocket.Handler(Wshandle))  
    ... 
}
And in main:
http.HandleFunc("/aa", aahandler)
bbhandler.Register(http.DefaultServeMux)
...
http.ListenAndServe()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论