Source file src/net/http/httptest/server.go

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Implementation of Server
     6  
     7  package httptest
     8  
     9  import (
    10  	"context"
    11  	"crypto/tls"
    12  	"crypto/x509"
    13  	"flag"
    14  	"fmt"
    15  	"internal/nettest"
    16  	"log"
    17  	"net"
    18  	"net/http"
    19  	"net/http/internal/testcert"
    20  	"os"
    21  	"runtime"
    22  	"strings"
    23  	"sync"
    24  	"testing"
    25  	"time"
    26  	_ "unsafe" // for linkname
    27  )
    28  
    29  // A Server is an HTTP server for use in end-to-end HTTP tests.
    30  //
    31  // Most tests should create a server with [NewTestServer].
    32  // The [Server.Client] method returns a client which sends requests to the test server.
    33  //
    34  //	// Create a test server and send a request to it.
    35  //	server := httptest.NewTestServer(t, handler)
    36  //	resp, err := server.Client().Get("http://www.example.com/")
    37  //
    38  // # Configuration
    39  //
    40  // Tests may change a Server's configuration prior to using it.
    41  // The configuration must not be changed after the first call to
    42  // [Server.Client], [Server.Start], or [Server.StartTLS].
    43  //
    44  //	// Configure a test server before using.
    45  //	server := httptest.NewTestServer(t, handler)
    46  //	server.Config.MaxHeaderBytes = 1024
    47  //	resp, err := server.Client().Get("http://www.example.com/")
    48  //
    49  // # Tests
    50  //
    51  // Servers created with [NewTestServer] will:
    52  //
    53  //   - Fail the test if the server handler panics with
    54  //     any value other than [http.ErrAbortHandler].
    55  //   - Register a Cleanup function to shut down the server at the end of the test.
    56  //
    57  // Servers created in any other way must be manually shut down with [Server.Close].
    58  //
    59  // # In-Memory Network
    60  //
    61  // A Server may use an in-memory network implementation or
    62  // listen on a local network loopback interface.
    63  // Most tests should use the in-memory network,
    64  // which avoids port exhaustion and other transient networking issues
    65  // and is suitable for use with the [testing/synctest] package.
    66  //
    67  // To use the in-memory network, create a server with [NewTestServer].
    68  // Do not call [Server.Start] or [Server.StartTLS].
    69  //
    70  // When using the in-memory network, the [http.Client] returned by [Server.Client]
    71  // is configured to send all requests to the server.
    72  // The client will direct HTTP and HTTPS requests,
    73  // regardless of destination address or hostname, to the server.
    74  // Requests do not need to use [Server.URL] as the base URL.
    75  //
    76  //	server := httptest.NewTestServer(t, handler)
    77  //	client := server.Client()
    78  //
    79  //	// All of these requests are sent to the test server.
    80  //	// https:// requests use TLS over the in-memory network.
    81  //	_, _ = client.Get("http://www.example.com/")
    82  //	_, _ = client.Get("https://go.dev/")
    83  //	_, _ = client.Get("http://10.0.0.1/")
    84  //
    85  // The [Server.Listener] field is not set when using the in-memory network.
    86  //
    87  // # Loopback Network
    88  //
    89  // To listen on a loopback interface, call [Server.Start] or [Server.StartTLS].
    90  // The server will listen on a system-chosen port.
    91  //
    92  // Loopback servers serve one of HTTP (when started with [Server.Start])
    93  // or HTTPS (when started with [Server.StartTLS]).
    94  //
    95  // When using the loopback network, the [http.Client] returned by [Server.Client]
    96  // is configured to send requests with a hostname of "example.com" or a subdomain
    97  // of ".example.com" to the server.
    98  //
    99  // Requests may also be sent to the server's loopback address.
   100  // The [Server.URL] field is set to a base URL containing the server's address.
   101  //
   102  //	server := httptest.NewTestServer(t, handler)
   103  //	server.Start()
   104  //	client := server.Client()
   105  //
   106  //	// This request is sent to the test server.
   107  //	_, _ = server.Client().Get(server.URL + "/")
   108  //
   109  //	// This request (using http.DefaultClient) is also sent to the test server,
   110  //	// since server.URL contains the server's local IP address.
   111  //	_, _ = http.Get(server.URL + "/")
   112  type Server struct {
   113  	// URL is the base URL of the server, of the form http://address:port
   114  	// with no trailing slash.
   115  	//
   116  	// It is set by the first call to Client, Start, or StartTLS.
   117  	//
   118  	// For servers listening on loopback, the address is the loopback IP address
   119  	// of the server.
   120  	//
   121  	// For servers using the in-memory network, this address is "example.com".
   122  	// Requests sent to servers using the in-memory network may use any address.
   123  	// It is not necessary to use this base URL.
   124  	URL string
   125  
   126  	// Listener is the network listener for servers listening on loopback.
   127  	// It is not set for servers using the in-memory network.
   128  	Listener net.Listener
   129  
   130  	// EnableHTTP2 controls whether HTTP/2 is enabled on the server.
   131  	// It must be set before calling Client, Start, or StartTLS.
   132  	EnableHTTP2 bool
   133  
   134  	// TLS is the optional TLS configuration, populated with a new config
   135  	// after TLS is started. If set on an unstarted server before StartTLS
   136  	// is called, existing fields are copied into the new config.
   137  	TLS *tls.Config
   138  
   139  	// Config may be changed before calling Client, Start, or StartTLS.
   140  	Config *http.Server
   141  
   142  	t testing.TB
   143  
   144  	// certificate is a parsed version of the TLS config certificate, if present.
   145  	certificate *x509.Certificate
   146  
   147  	// startOnce is used to start fakenet servers once.
   148  	startOnce sync.Once
   149  
   150  	// started indicates whether the server has been started.
   151  	started bool
   152  
   153  	// Fake network listeners, one for HTTP and one for HTTPS.
   154  	fakeListener    *nettest.Listener
   155  	fakeTLSListener *nettest.Listener
   156  
   157  	// wg counts the number of outstanding HTTP requests on this server.
   158  	// Close blocks until all requests are finished.
   159  	wg sync.WaitGroup
   160  
   161  	mu     sync.Mutex // guards closed and conns
   162  	closed bool
   163  	conns  map[net.Conn]http.ConnState // except terminal states
   164  
   165  	// client is configured for use with the server.
   166  	// Its transport is automatically closed when Close is called.
   167  	client *http.Client
   168  }
   169  
   170  // NewTestServer returns a new [Server] for a test.
   171  // The server will use an in-memory network implementation by default.
   172  //
   173  // If the handler is nil, the server will serve 500 responses to all requests.
   174  // It will not use [http.DefaultServeMux].
   175  //
   176  // See the [Server] documentation for more details.
   177  func NewTestServer(t testing.TB, handler http.Handler) *Server {
   178  	s := &Server{
   179  		t:      t,
   180  		Config: &http.Server{Handler: testServerHandler{t: t, h: handler}},
   181  	}
   182  	t.Cleanup(func() {
   183  		s.Close()
   184  	})
   185  	return s
   186  }
   187  
   188  type testServerHandler struct {
   189  	t testing.TB
   190  	h http.Handler
   191  }
   192  
   193  func (h testServerHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
   194  	defer func() {
   195  		if err := recover(); err != nil {
   196  			if err != http.ErrAbortHandler {
   197  				// This is the same logging http.Server would do,
   198  				// but we can put it into the test output rather than stderr.
   199  				const size = 64 << 10
   200  				buf := make([]byte, size)
   201  				buf = buf[:runtime.Stack(buf, false)]
   202  				h.t.Errorf("httptest: panic in server handler: %v\n%s", err, buf)
   203  			}
   204  			// Convert panic to ErrAbortHandler to suppress http.Server's logging.
   205  			panic(http.ErrAbortHandler)
   206  		}
   207  	}()
   208  	if h.h != nil {
   209  		h.h.ServeHTTP(w, req)
   210  	} else {
   211  		w.WriteHeader(500)
   212  	}
   213  }
   214  
   215  func newLocalListener() net.Listener {
   216  	if serveFlag != "" {
   217  		l, err := net.Listen("tcp", serveFlag)
   218  		if err != nil {
   219  			panic(fmt.Sprintf("httptest: failed to listen on %v: %v", serveFlag, err))
   220  		}
   221  		return l
   222  	}
   223  	l, err := net.Listen("tcp", "127.0.0.1:0")
   224  	if err != nil {
   225  		if l, err = net.Listen("tcp6", "[::1]:0"); err != nil {
   226  			panic(fmt.Sprintf("httptest: failed to listen on a port: %v", err))
   227  		}
   228  	}
   229  	return l
   230  }
   231  
   232  // When debugging a particular http server-based test,
   233  // this flag lets you run
   234  //
   235  //	go test -run='^BrokenTest$' -httptest.serve=127.0.0.1:8000
   236  //
   237  // to start the broken server so you can interact with it manually.
   238  // We only register this flag if it looks like the caller knows about it
   239  // and is trying to use it as we don't want to pollute flags and this
   240  // isn't really part of our API. Don't depend on this.
   241  var serveFlag string
   242  
   243  func init() {
   244  	if strSliceContainsPrefix(os.Args, "-httptest.serve=") || strSliceContainsPrefix(os.Args, "--httptest.serve=") {
   245  		flag.StringVar(&serveFlag, "httptest.serve", "", "if non-empty, httptest.NewServer serves on this address and blocks.")
   246  	}
   247  }
   248  
   249  func strSliceContainsPrefix(v []string, pre string) bool {
   250  	for _, s := range v {
   251  		if strings.HasPrefix(s, pre) {
   252  			return true
   253  		}
   254  	}
   255  	return false
   256  }
   257  
   258  // NewServer starts and returns a new [Server] listening on a
   259  // local network loopback interface.
   260  // This is equivalent to calling [NewUnstartedServer] followed by [Server.Start].
   261  //
   262  // The caller should call [Server.Close] when finished, to shut it down.
   263  //
   264  // Most users should use [NewTestServer] instead.
   265  // See the [Server] documentation for details.
   266  func NewServer(handler http.Handler) *Server {
   267  	ts := NewUnstartedServer(handler)
   268  	ts.Start()
   269  	return ts
   270  }
   271  
   272  // NewUnstartedServer returns a new [Server] listening on a
   273  // local network loopback interface. It does not start the server.
   274  //
   275  // After changing the server's configuration, the caller should
   276  // call [Server.Start] or [Server.StartTLS].
   277  //
   278  // The caller should call [Server.Close] when finished, to shut it down.
   279  //
   280  // Most users should use [NewTestServer] instead.
   281  // See the [Server] documentation for details.
   282  func NewUnstartedServer(handler http.Handler) *Server {
   283  	return &Server{
   284  		Listener: newLocalListener(),
   285  		Config:   &http.Server{Handler: handler},
   286  	}
   287  }
   288  
   289  func (s *Server) startCommon(useLoopback bool) {
   290  	s.mu.Lock()
   291  	defer s.mu.Unlock()
   292  	if s.started {
   293  		panic("Server already started")
   294  	}
   295  	if s.closed {
   296  		panic("Start of closed Server")
   297  	}
   298  	s.started = true
   299  	if s.t != nil && useLoopback {
   300  		// We're being called from Start or StartTLS.
   301  		// Don't try to start the server again when Client is called.
   302  		s.startOnce.Do(func() {})
   303  
   304  		// NewTestServer servers create their listener at start time.
   305  		//
   306  		// We might want to permit the user to provide their own Listener
   307  		// in the future. For now, we panic.
   308  		if s.Listener != nil {
   309  			panic("Server.Listener is unexpectedly set")
   310  		}
   311  		s.Listener = newLocalListener()
   312  	}
   313  	s.wrap()
   314  }
   315  
   316  // Start starts a server on a local loopback network interface.
   317  //
   318  // The server should have been created by [NewTestServer] or [NewUnstartedServer].
   319  func (s *Server) Start() {
   320  	s.startCommon(true)
   321  
   322  	tr := &http.Transport{}
   323  	s.client = &http.Client{Transport: tr}
   324  	if s.Listener == nil {
   325  		return
   326  	}
   327  	dialer := net.Dialer{}
   328  	// User code may set either of Dial or DialContext, with DialContext taking precedence.
   329  	// We set DialContext here to preserve any context values that are passed in,
   330  	// but fall back to Dial if the user has set it.
   331  	tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
   332  		if tr.Dial != nil {
   333  			return tr.Dial(network, addr)
   334  		}
   335  		if addr == "example.com:80" || strings.HasSuffix(addr, ".example.com:80") {
   336  			addr = s.Listener.Addr().String()
   337  		}
   338  		return dialer.DialContext(ctx, network, addr)
   339  	}
   340  	s.URL = "http://" + s.Listener.Addr().String()
   341  	s.goServe(s.Listener)
   342  	if serveFlag != "" {
   343  		fmt.Fprintln(os.Stderr, "httptest: serving on", s.URL)
   344  		select {}
   345  	}
   346  }
   347  
   348  func (s *Server) initTLS() (tlsClientConfig *tls.Config, err error) {
   349  	cert, err := tls.X509KeyPair(testcert.LocalhostCert, testcert.LocalhostKey)
   350  	if err != nil {
   351  		return nil, err
   352  	}
   353  
   354  	existingConfig := s.TLS
   355  	if existingConfig != nil {
   356  		s.TLS = existingConfig.Clone()
   357  	} else {
   358  		s.TLS = new(tls.Config)
   359  	}
   360  	if s.TLS.NextProtos == nil {
   361  		nextProtos := []string{"http/1.1"}
   362  		if s.EnableHTTP2 {
   363  			nextProtos = []string{"h2"}
   364  		}
   365  		s.TLS.NextProtos = nextProtos
   366  	}
   367  	if len(s.TLS.Certificates) == 0 {
   368  		s.TLS.Certificates = []tls.Certificate{cert}
   369  	}
   370  	s.certificate, err = x509.ParseCertificate(s.TLS.Certificates[0].Certificate[0])
   371  	if err != nil {
   372  		return nil, err
   373  	}
   374  	certpool := x509.NewCertPool()
   375  	certpool.AddCert(s.certificate)
   376  	return &tls.Config{
   377  		RootCAs: certpool,
   378  	}, nil
   379  }
   380  
   381  // Start starts TLS on a server on a local loopback network interface.
   382  //
   383  // The server should have been created by [NewTestServer] or [NewUnstartedServer].
   384  func (s *Server) StartTLS() {
   385  	s.startCommon(true)
   386  
   387  	s.client = &http.Client{}
   388  
   389  	tlsClientConfig, err := s.initTLS()
   390  	if err != nil {
   391  		panic(fmt.Sprintf("httptest: NewTLSServer: %v", err))
   392  	}
   393  
   394  	tr := &http.Transport{
   395  		TLSClientConfig:   tlsClientConfig,
   396  		ForceAttemptHTTP2: s.EnableHTTP2,
   397  	}
   398  	s.client.Transport = tr
   399  
   400  	if s.Listener == nil {
   401  		return
   402  	}
   403  	dialer := net.Dialer{}
   404  	tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
   405  		if tr.Dial != nil {
   406  			return tr.Dial(network, addr)
   407  		}
   408  		if addr == "example.com:443" || strings.HasSuffix(addr, ".example.com:443") {
   409  			addr = s.Listener.Addr().String()
   410  		}
   411  		return dialer.DialContext(ctx, network, addr)
   412  	}
   413  	s.Listener = tls.NewListener(s.Listener, s.TLS)
   414  	s.URL = "https://" + s.Listener.Addr().String()
   415  	s.goServe(s.Listener)
   416  }
   417  
   418  func (s *Server) startFakeNet() {
   419  	s.startCommon(false)
   420  
   421  	s.client = &http.Client{}
   422  
   423  	tlsClientConfig, err := s.initTLS()
   424  	if err != nil {
   425  		panic(fmt.Sprintf("httptest: NewTestServer: %v", err))
   426  	}
   427  
   428  	tr := &http.Transport{
   429  		TLSClientConfig:   tlsClientConfig,
   430  		ForceAttemptHTTP2: s.EnableHTTP2,
   431  	}
   432  	s.client.Transport = tr
   433  
   434  	s.fakeListener = nettest.NewListener()
   435  	s.fakeTLSListener = nettest.NewListener()
   436  
   437  	// Set InsecureSkipVerify rather than depending on a specific server hostname.
   438  	tr.TLSClientConfig.InsecureSkipVerify = true
   439  	tr.DialContext = func(ctx context.Context, network, address string) (net.Conn, error) {
   440  		return s.fakeListener.NewConn(), nil
   441  	}
   442  	tr.DialTLSContext = func(ctx context.Context, network, address string) (net.Conn, error) {
   443  		return tls.Client(s.fakeTLSListener.NewConn(), tr.TLSClientConfig), nil
   444  	}
   445  	s.URL = "http://example.com"
   446  	s.goServe(s.fakeListener)
   447  	s.goServe(tls.NewListener(s.fakeTLSListener, s.TLS))
   448  }
   449  
   450  // NewTLSServer starts and returns a new [Server] using TLS and listening on a
   451  // local network loopback interface.
   452  // This is equivalent to calling [NewUnstartedServer] followed by [Server.StartTLS].
   453  //
   454  // The caller should call [Server.Close] when finished, to shut it down.
   455  //
   456  // Most users should use [NewTestServer] instead.
   457  // See the [Server] documentation for details.
   458  func NewTLSServer(handler http.Handler) *Server {
   459  	ts := NewUnstartedServer(handler)
   460  	ts.StartTLS()
   461  	return ts
   462  }
   463  
   464  type closeIdleTransport interface {
   465  	CloseIdleConnections()
   466  }
   467  
   468  // Close shuts down the server and blocks until all outstanding
   469  // requests on this server have completed.
   470  func (s *Server) Close() {
   471  	s.mu.Lock()
   472  	if !s.closed {
   473  		s.closed = true
   474  		if s.Listener != nil {
   475  			s.Listener.Close()
   476  		}
   477  		if s.fakeListener != nil {
   478  			s.fakeListener.Close()
   479  			s.fakeTLSListener.Close()
   480  		}
   481  		s.Config.SetKeepAlivesEnabled(false)
   482  		for c, st := range s.conns {
   483  			// Force-close any idle connections (those between
   484  			// requests) and new connections (those which connected
   485  			// but never sent a request). StateNew connections are
   486  			// super rare and have only been seen (in
   487  			// previously-flaky tests) in the case of
   488  			// socket-late-binding races from the http Client
   489  			// dialing this server and then getting an idle
   490  			// connection before the dial completed. There is thus
   491  			// a connected connection in StateNew with no
   492  			// associated Request. We only close StateIdle and
   493  			// StateNew because they're not doing anything. It's
   494  			// possible StateNew is about to do something in a few
   495  			// milliseconds, but a previous CL to check again in a
   496  			// few milliseconds wasn't liked (early versions of
   497  			// https://golang.org/cl/15151) so now we just
   498  			// forcefully close StateNew. The docs for Server.Close say
   499  			// we wait for "outstanding requests", so we don't close things
   500  			// in StateActive.
   501  			if st == http.StateIdle || st == http.StateNew {
   502  				s.closeConn(c)
   503  			}
   504  		}
   505  		// If this server doesn't shut down in 5 seconds, tell the user why.
   506  		t := time.AfterFunc(5*time.Second, s.logCloseHangDebugInfo)
   507  		defer t.Stop()
   508  	}
   509  	s.mu.Unlock()
   510  
   511  	// Not part of httptest.Server's correctness, but assume most
   512  	// users of httptest.Server will be using the standard
   513  	// transport, so help them out and close any idle connections for them.
   514  	if t, ok := http.DefaultTransport.(closeIdleTransport); ok {
   515  		t.CloseIdleConnections()
   516  	}
   517  
   518  	// Also close the client idle connections.
   519  	if s.client != nil {
   520  		if t, ok := s.client.Transport.(closeIdleTransport); ok {
   521  			t.CloseIdleConnections()
   522  		}
   523  	}
   524  	s.wg.Wait()
   525  }
   526  
   527  func (s *Server) logCloseHangDebugInfo() {
   528  	s.mu.Lock()
   529  	defer s.mu.Unlock()
   530  	var buf strings.Builder
   531  	buf.WriteString("httptest.Server blocked in Close after 5 seconds, waiting for connections:\n")
   532  	for c, st := range s.conns {
   533  		fmt.Fprintf(&buf, "  %T %p %v in state %v\n", c, c, c.RemoteAddr(), st)
   534  	}
   535  	log.Print(buf.String())
   536  }
   537  
   538  // CloseClientConnections closes any open HTTP connections to the test Server.
   539  func (s *Server) CloseClientConnections() {
   540  	s.mu.Lock()
   541  	nconn := len(s.conns)
   542  	ch := make(chan struct{}, nconn)
   543  	for c := range s.conns {
   544  		go s.closeConnChan(c, ch)
   545  	}
   546  	s.mu.Unlock()
   547  
   548  	// Wait for outstanding closes to finish.
   549  	//
   550  	// Out of paranoia for making a late change in Go 1.6, we
   551  	// bound how long this can wait, since golang.org/issue/14291
   552  	// isn't fully understood yet. At least this should only be used
   553  	// in tests.
   554  	timer := time.NewTimer(5 * time.Second)
   555  	defer timer.Stop()
   556  	for i := 0; i < nconn; i++ {
   557  		select {
   558  		case <-ch:
   559  		case <-timer.C:
   560  			// Too slow. Give up.
   561  			return
   562  		}
   563  	}
   564  }
   565  
   566  // Certificate returns the certificate used by the server, or nil if
   567  // the server doesn't use TLS.
   568  func (s *Server) Certificate() *x509.Certificate {
   569  	return s.certificate
   570  }
   571  
   572  // Client returns an HTTP client configured for making requests to the server.
   573  // It is configured to trust the server's TLS test certificate and will
   574  // close its idle connections on [Server.Close].
   575  func (s *Server) Client() *http.Client {
   576  	if s.t != nil {
   577  		s.startOnce.Do(s.startFakeNet)
   578  	}
   579  	return s.client
   580  }
   581  
   582  func (s *Server) goServe(li net.Listener) {
   583  	s.wg.Add(1)
   584  	go func() {
   585  		defer s.wg.Done()
   586  		s.Config.Serve(li)
   587  	}()
   588  }
   589  
   590  // wrap installs the connection state-tracking hook to know which
   591  // connections are idle.
   592  func (s *Server) wrap() {
   593  	oldHook := s.Config.ConnState
   594  	s.Config.ConnState = func(c net.Conn, cs http.ConnState) {
   595  		s.mu.Lock()
   596  		defer s.mu.Unlock()
   597  
   598  		switch cs {
   599  		case http.StateNew:
   600  			if _, exists := s.conns[c]; exists {
   601  				panic("invalid state transition")
   602  			}
   603  			if s.conns == nil {
   604  				s.conns = make(map[net.Conn]http.ConnState)
   605  			}
   606  			// Add c to the set of tracked conns and increment it to the
   607  			// waitgroup.
   608  			s.wg.Add(1)
   609  			s.conns[c] = cs
   610  			if s.closed {
   611  				// Probably just a socket-late-binding dial from
   612  				// the default transport that lost the race (and
   613  				// thus this connection is now idle and will
   614  				// never be used).
   615  				s.closeConn(c)
   616  			}
   617  		case http.StateActive:
   618  			if oldState, ok := s.conns[c]; ok {
   619  				if oldState != http.StateNew && oldState != http.StateIdle {
   620  					panic("invalid state transition")
   621  				}
   622  				s.conns[c] = cs
   623  			}
   624  		case http.StateIdle:
   625  			if oldState, ok := s.conns[c]; ok {
   626  				if oldState != http.StateActive {
   627  					panic("invalid state transition")
   628  				}
   629  				s.conns[c] = cs
   630  			}
   631  			if s.closed {
   632  				s.closeConn(c)
   633  			}
   634  		case http.StateHijacked, http.StateClosed:
   635  			// Remove c from the set of tracked conns and decrement it from the
   636  			// waitgroup, unless it was previously removed.
   637  			if _, ok := s.conns[c]; ok {
   638  				delete(s.conns, c)
   639  				// Keep Close from returning until the user's ConnState hook
   640  				// (if any) finishes.
   641  				defer s.wg.Done()
   642  			}
   643  		}
   644  		if oldHook != nil {
   645  			oldHook(c, cs)
   646  		}
   647  	}
   648  }
   649  
   650  // closeConn closes c.
   651  // s.mu must be held.
   652  func (s *Server) closeConn(c net.Conn) { s.closeConnChan(c, nil) }
   653  
   654  // closeConnChan is like closeConn, but takes an optional channel to receive a value
   655  // when the goroutine closing c is done.
   656  func (s *Server) closeConnChan(c net.Conn, done chan<- struct{}) {
   657  	c.Close()
   658  	if done != nil {
   659  		done <- struct{}{}
   660  	}
   661  }
   662  

View as plain text