How to pass net/http to other package

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

How to pass net/http to other package

问题

我使用以下代码片段来创建一个HTTP服务器。

在主包中:

  1. http.HandleFunc("/aa", aahandler)
  2. http.Handle("/echo", websocket.Handler(bbhandler.Wshandle))
  3. ...
  4. http.ListenAndServe()

bbhandler 是我自定义的包。
以上代码可以正常工作。

现在我想在 bbhandler 中添加一个 Register 函数。

  1. Register() {
  2. http.Handle("/echo", websocket.Handler(Wshandle))
  3. ...
  4. }

然后,主包中的代码将变为:

  1. http.HandleFunc("/aa", aahandler)
  2. bbhandler.Register()
  3. ...
  4. http.ListenAndServe()

但是上述代码似乎不起作用,因为主程序不会处理 /echo,看起来 bbhandler.Register 没有将 /echo 添加到主程序的 http 中。那么我该如何将主程序的 http 传递给 bbhandler 并添加 /echo 处理函数呢?

英文:

I use below code snippet for http server.

in main package:

  1. http.HandleFunc("/aa", aahandler)
  2. http.Handle("/echo", websocket.Handler(bbhandler.Wshandle))
  3. ...
  4. http.ListenAndServe()

the bbhandler is self-defined package.
Above code works.

Now I want to add a function Register in bbhandler.

  1. Register() {
  2. http.Handle("/echo", websocket.Handler(Wshandle))
  3. ...
  4. }

and main package code snippet will become as:

  1. http.HandleFunc("/aa", aahandler)
  2. bbhandler.Register()
  3. ...
  4. 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,让调用者对处理程序的添加位置有控制,那将是更好的设计:

  1. Register(mux *http.ServeMux) {
  2. mux.Handle("/echo", websocket.Handler(Wshandle))
  3. ...
  4. }

main函数中:

  1. http.HandleFunc("/aa", aahandler)
  2. bbhandler.Register(http.DefaultServeMux)
  3. ...
  4. 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:

  1. Register(mux *http.ServeMux) {
  2. mux.Handle("/echo", websocket.Handler(Wshandle))
  3. ...
  4. }

And in main:

  1. http.HandleFunc("/aa", aahandler)
  2. bbhandler.Register(http.DefaultServeMux)
  3. ...
  4. 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:

确定