How to pass net/http to other package

huangapple go评论81阅读模式
英文:

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

huangapple
  • 本文由 发表于 2014年5月10日 22:25:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/23582212.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定