Pergunta

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.

Foi útil?

Solução

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()
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top