Skip to content

Commit

Permalink
Use pointer for Host.ServeMux
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcoPolo committed Aug 25, 2023
1 parent 1af5d3b commit ed42d2f
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions p2p/http/libp2phttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,12 @@ type Host struct {
// InsecureAllowHTTP indicates if the server is allowed to serve unencrypted
// HTTP requests over TCP.
InsecureAllowHTTP bool
// ServeMux is the http.ServeMux used by the server to serve requests. The
// zero value is a new serve mux. Users may manually add handlers to this
// ServeMux is the http.ServeMux used by the server to serve requests. If nil,
// new serve mux will be allocated. Users may manually add handlers to this
// mux instead of using `SetHTTPHandler`, but if they do, they should also
// update the WellKnownHandler's protocol mapping.
ServeMux http.ServeMux
ServeMux *http.ServeMux
initializeServeMux sync.Once

// DefaultClientRoundTripper is the default http.RoundTripper for clients to
// use when making requests over an HTTP transport. This must be an
Expand Down Expand Up @@ -166,6 +167,12 @@ func (h *Host) httpTransportInit() {
})
}

func (h *Host) serveMuxInit() {
h.initializeServeMux.Do(func() {
h.ServeMux = http.NewServeMux()
})
}

func (h *Host) Addrs() []ma.Multiaddr {
h.httpTransportInit()
<-h.httpTransport.waitingForListeners
Expand Down Expand Up @@ -193,6 +200,7 @@ func (h *Host) Serve() error {
}
}

h.serveMuxInit()
h.ServeMux.Handle("/.well-known/libp2p", &h.WellKnownHandler)

h.httpTransportInit()
Expand Down Expand Up @@ -227,7 +235,7 @@ func (h *Host) Serve() error {
h.httpTransport.listenAddrs = append(h.httpTransport.listenAddrs, h.StreamHost.Addrs()...)

go func() {
errCh <- http.Serve(listener, &h.ServeMux)
errCh <- http.Serve(listener, h.ServeMux)
}()
}

Expand Down Expand Up @@ -274,15 +282,15 @@ func (h *Host) Serve() error {
if parsedAddr.useHTTPS {
go func() {
srv := http.Server{
Handler: &h.ServeMux,
Handler: h.ServeMux,
TLSConfig: h.TLSConfig,
}
errCh <- srv.ServeTLS(l, "", "")
}()
h.httpTransport.listenAddrs = append(h.httpTransport.listenAddrs, listenAddr)
} else if h.InsecureAllowHTTP {
go func() {
errCh <- http.Serve(l, &h.ServeMux)
errCh <- http.Serve(l, h.ServeMux)
}()
h.httpTransport.listenAddrs = append(h.httpTransport.listenAddrs, listenAddr)
} else {
Expand Down Expand Up @@ -346,6 +354,7 @@ func (h *Host) SetHTTPHandlerAtPath(p protocol.ID, path string, handler http.Han
path += "/"
}
h.WellKnownHandler.AddProtocolMeta(p, ProtocolMeta{Path: path})
h.serveMuxInit()
h.ServeMux.Handle(path, http.StripPrefix(path, handler))
}

Expand Down

0 comments on commit ed42d2f

Please sign in to comment.