服务器启动后如何在http.Handle()中更改处理程序?

我正在使用socketio “ github.com/googollee/go-socket.io” </ code>

出于某种原因,我必须创建一个新的* socketio.server并将其注册到已经在旧* socketio.server中注册的“ / static /” </ code>中。 </ p>

这意味着在服务器启动后,我必须在 http.Handle(“ / socket.io/”,ioserver)</ code>中替换处理程序ioserver。 </ p>

下面是我的代码的一部分,当发生某些情况时,我将创建一个新的ioserver。 我希望新的ioserver成为 http.Handle(“ / socket.io/”,ioserver)</ code> </ p>

  ioserver中的处理程序,_ = socketio  .NewServer(nil)
http.Handle(“ / socket.io/”,ioserver)
log.Fatal(http.ListenAndServe(“:81”,nil))
</ code> </ pre>
< / DIV>

展开原文

原文

I am using socketio "github.com/googollee/go-socket.io" in Go. For some reason, I have to make a new *socketio.server and register it to "/static/" which is already been registered with the old *socketio.server.

It means that I have to replace the handler ioserver in http.Handle("/socket.io/", ioserver) after the server has been started.

Below is part of my code, when something happens, I will create a new ioserver. I want the new ioserver to be the handler in http.Handle("/socket.io/", ioserver)

ioserver, _ = socketio.NewServer(nil)
http.Handle("/socket.io/", ioserver)
log.Fatal(http.ListenAndServe(":81", nil))

1个回答

An application cannot swap handlers in the mux, but it can write a handler that swaps between other handlers:

type swapper struct {
    mu sync.Mutex
    h http.Handler
}

func (s *swapper) setHandler(h http.Handler) {
    s.mu.Lock()
    s.h = h
    s.mu.Unlock()
}

func (w *swapper) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    s.mu.Lock()
    h := s.h
    s.mu.Unlock()
    h.ServeHTTP(w, r)
}

Register it like this:

ioserver, _ = socketio.NewServer(nil)
s := &swapper{}
s.setHandler(ioserver)
http.Handle("/socket.io/", s)
log.Fatal(http.ListenAndServe(":81", nil))

At any time, the application can call s.setHandler to swap in a new handler.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐