@@ -113,11 +113,12 @@ type Host struct {
113
113
// InsecureAllowHTTP indicates if the server is allowed to serve unencrypted
114
114
// HTTP requests over TCP.
115
115
InsecureAllowHTTP bool
116
- // ServeMux is the http.ServeMux used by the server to serve requests. The
117
- // zero value is a new serve mux. Users may manually add handlers to this
116
+ // ServeMux is the http.ServeMux used by the server to serve requests. If nil,
117
+ // new serve mux will be allocated . Users may manually add handlers to this
118
118
// mux instead of using `SetHTTPHandler`, but if they do, they should also
119
119
// update the WellKnownHandler's protocol mapping.
120
- ServeMux http.ServeMux
120
+ ServeMux * http.ServeMux
121
+ initializeServeMux sync.Once
121
122
122
123
// DefaultClientRoundTripper is the default http.RoundTripper for clients to
123
124
// use when making requests over an HTTP transport. This must be an
@@ -166,6 +167,12 @@ func (h *Host) httpTransportInit() {
166
167
})
167
168
}
168
169
170
+ func (h * Host ) serveMuxInit () {
171
+ h .initializeServeMux .Do (func () {
172
+ h .ServeMux = http .NewServeMux ()
173
+ })
174
+ }
175
+
169
176
func (h * Host ) Addrs () []ma.Multiaddr {
170
177
h .httpTransportInit ()
171
178
<- h .httpTransport .waitingForListeners
@@ -193,6 +200,7 @@ func (h *Host) Serve() error {
193
200
}
194
201
}
195
202
203
+ h .serveMuxInit ()
196
204
h .ServeMux .Handle ("/.well-known/libp2p" , & h .WellKnownHandler )
197
205
198
206
h .httpTransportInit ()
@@ -227,7 +235,7 @@ func (h *Host) Serve() error {
227
235
h .httpTransport .listenAddrs = append (h .httpTransport .listenAddrs , h .StreamHost .Addrs ()... )
228
236
229
237
go func () {
230
- errCh <- http .Serve (listener , & h .ServeMux )
238
+ errCh <- http .Serve (listener , h .ServeMux )
231
239
}()
232
240
}
233
241
@@ -274,15 +282,15 @@ func (h *Host) Serve() error {
274
282
if parsedAddr .useHTTPS {
275
283
go func () {
276
284
srv := http.Server {
277
- Handler : & h .ServeMux ,
285
+ Handler : h .ServeMux ,
278
286
TLSConfig : h .TLSConfig ,
279
287
}
280
288
errCh <- srv .ServeTLS (l , "" , "" )
281
289
}()
282
290
h .httpTransport .listenAddrs = append (h .httpTransport .listenAddrs , listenAddr )
283
291
} else if h .InsecureAllowHTTP {
284
292
go func () {
285
- errCh <- http .Serve (l , & h .ServeMux )
293
+ errCh <- http .Serve (l , h .ServeMux )
286
294
}()
287
295
h .httpTransport .listenAddrs = append (h .httpTransport .listenAddrs , listenAddr )
288
296
} else {
@@ -346,6 +354,7 @@ func (h *Host) SetHTTPHandlerAtPath(p protocol.ID, path string, handler http.Han
346
354
path += "/"
347
355
}
348
356
h .WellKnownHandler .AddProtocolMeta (p , ProtocolMeta {Path : path })
357
+ h .serveMuxInit ()
349
358
h .ServeMux .Handle (path , http .StripPrefix (path , handler ))
350
359
}
351
360
0 commit comments