gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/gmhttp/httptest/server.go (about)

     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  	"flag"
    11  	"fmt"
    12  	"log"
    13  	"net"
    14  	"os"
    15  	"strings"
    16  	"sync"
    17  	"time"
    18  
    19  	http "gitee.com/ks-custle/core-gm/gmhttp"
    20  	"gitee.com/ks-custle/core-gm/gmhttp/internal/testcert"
    21  	tls "gitee.com/ks-custle/core-gm/gmtls"
    22  	"gitee.com/ks-custle/core-gm/x509"
    23  )
    24  
    25  // A Server is an HTTP server listening on a system-chosen port on the
    26  // local loopback interface, for use in end-to-end HTTP tests.
    27  type Server struct {
    28  	URL      string // base URL of form http://ipaddr:port with no trailing slash
    29  	Listener net.Listener
    30  
    31  	// EnableHTTP2 controls whether HTTP/2 is enabled
    32  	// on the server. It must be set between calling
    33  	// NewUnstartedServer and calling Server.StartTLS.
    34  	EnableHTTP2 bool
    35  
    36  	// TLS is the optional TLS configuration, populated with a new config
    37  	// after TLS is started. If set on an unstarted server before StartTLS
    38  	// is called, existing fields are copied into the new config.
    39  	TLS *tls.Config
    40  
    41  	// Config may be changed after calling NewUnstartedServer and
    42  	// before Start or StartTLS.
    43  	Config *http.Server
    44  
    45  	// certificate is a parsed version of the TLS config certificate, if present.
    46  	certificate *x509.Certificate
    47  
    48  	// wg counts the number of outstanding HTTP requests on this server.
    49  	// Close blocks until all requests are finished.
    50  	wg sync.WaitGroup
    51  
    52  	mu     sync.Mutex // guards closed and conns
    53  	closed bool
    54  	conns  map[net.Conn]http.ConnState // except terminal states
    55  
    56  	// client is configured for use with the server.
    57  	// Its transport is automatically closed when Close is called.
    58  	client *http.Client
    59  }
    60  
    61  func newLocalListener() net.Listener {
    62  	if serveFlag != "" {
    63  		l, err := net.Listen("tcp", serveFlag)
    64  		if err != nil {
    65  			panic(fmt.Sprintf("httptest: failed to listen on %v: %v", serveFlag, err))
    66  		}
    67  		return l
    68  	}
    69  	l, err := net.Listen("tcp", "127.0.0.1:0")
    70  	if err != nil {
    71  		if l, err = net.Listen("tcp6", "[::1]:0"); err != nil {
    72  			panic(fmt.Sprintf("httptest: failed to listen on a port: %v", err))
    73  		}
    74  	}
    75  	return l
    76  }
    77  
    78  // When debugging a particular http server-based test,
    79  // this flag lets you run
    80  //
    81  //	go test -run=BrokenTest -httptest.serve=127.0.0.1:8000
    82  //
    83  // to start the broken server so you can interact with it manually.
    84  // We only register this flag if it looks like the caller knows about it
    85  // and is trying to use it as we don't want to pollute flags and this
    86  // isn't really part of our API. Don't depend on this.
    87  var serveFlag string
    88  
    89  func init() {
    90  	if strSliceContainsPrefix(os.Args, "-httptest.serve=") || strSliceContainsPrefix(os.Args, "--httptest.serve=") {
    91  		flag.StringVar(&serveFlag, "httptest.serve", "", "if non-empty, httptest.NewServer serves on this address and blocks.")
    92  	}
    93  }
    94  
    95  func strSliceContainsPrefix(v []string, pre string) bool {
    96  	for _, s := range v {
    97  		if strings.HasPrefix(s, pre) {
    98  			return true
    99  		}
   100  	}
   101  	return false
   102  }
   103  
   104  // NewServer starts and returns a new Server.
   105  // The caller should call Close when finished, to shut it down.
   106  func NewServer(handler http.Handler) *Server {
   107  	ts := NewUnstartedServer(handler)
   108  	ts.Start()
   109  	return ts
   110  }
   111  
   112  // NewUnstartedServer returns a new Server but doesn't start it.
   113  //
   114  // After changing its configuration, the caller should call Start or
   115  // StartTLS.
   116  //
   117  // The caller should call Close when finished, to shut it down.
   118  func NewUnstartedServer(handler http.Handler) *Server {
   119  	return &Server{
   120  		Listener: newLocalListener(),
   121  		Config:   &http.Server{Handler: handler},
   122  	}
   123  }
   124  
   125  // Start starts a server from NewUnstartedServer.
   126  func (s *Server) Start() {
   127  	if s.URL != "" {
   128  		panic("Server already started")
   129  	}
   130  	if s.client == nil {
   131  		s.client = &http.Client{Transport: &http.Transport{}}
   132  	}
   133  	//goland:noinspection HttpUrlsUsage
   134  	s.URL = "http://" + s.Listener.Addr().String()
   135  	s.wrap()
   136  	s.goServe()
   137  	if serveFlag != "" {
   138  		_, _ = fmt.Fprintln(os.Stderr, "httptest: serving on", s.URL)
   139  		select {}
   140  	}
   141  }
   142  
   143  // StartTLS starts TLS on a server from NewUnstartedServer.
   144  func (s *Server) StartTLS() {
   145  	if s.URL != "" {
   146  		panic("Server already started")
   147  	}
   148  	if s.client == nil {
   149  		s.client = &http.Client{Transport: &http.Transport{}}
   150  	}
   151  	cert, err := tls.X509KeyPair(testcert.LocalhostCert, testcert.LocalhostKey)
   152  	if err != nil {
   153  		panic(fmt.Sprintf("httptest: NewTLSServer: %v", err))
   154  	}
   155  
   156  	existingConfig := s.TLS
   157  	if existingConfig != nil {
   158  		s.TLS = existingConfig.Clone()
   159  	} else {
   160  		s.TLS = new(tls.Config)
   161  	}
   162  	if s.TLS.NextProtos == nil {
   163  		nextProtos := []string{"http/1.1"}
   164  		if s.EnableHTTP2 {
   165  			nextProtos = []string{"h2"}
   166  		}
   167  		s.TLS.NextProtos = nextProtos
   168  	}
   169  	if len(s.TLS.Certificates) == 0 {
   170  		s.TLS.Certificates = []tls.Certificate{cert}
   171  	}
   172  	s.certificate, err = x509.ParseCertificate(s.TLS.Certificates[0].Certificate[0])
   173  	if err != nil {
   174  		panic(fmt.Sprintf("httptest: NewTLSServer: %v", err))
   175  	}
   176  	certpool := x509.NewCertPool()
   177  	certpool.AddCert(s.certificate)
   178  	s.client.Transport = &http.Transport{
   179  		TLSClientConfig: &tls.Config{
   180  			RootCAs: certpool,
   181  		},
   182  		ForceAttemptHTTP2: s.EnableHTTP2,
   183  	}
   184  	s.Listener = tls.NewListener(s.Listener, s.TLS)
   185  	s.URL = "https://" + s.Listener.Addr().String()
   186  	s.wrap()
   187  	s.goServe()
   188  }
   189  
   190  // NewTLSServer starts and returns a new Server using TLS.
   191  // The caller should call Close when finished, to shut it down.
   192  func NewTLSServer(handler http.Handler) *Server {
   193  	ts := NewUnstartedServer(handler)
   194  	ts.StartTLS()
   195  	return ts
   196  }
   197  
   198  type closeIdleTransport interface {
   199  	CloseIdleConnections()
   200  }
   201  
   202  // Close shuts down the server and blocks until all outstanding
   203  // requests on this server have completed.
   204  func (s *Server) Close() {
   205  	s.mu.Lock()
   206  	if !s.closed {
   207  		s.closed = true
   208  		_ = s.Listener.Close()
   209  		s.Config.SetKeepAlivesEnabled(false)
   210  		for c, st := range s.conns {
   211  			// Force-close any idle connections (those between
   212  			// requests) and new connections (those which connected
   213  			// but never sent a request). StateNew connections are
   214  			// super rare and have only been seen (in
   215  			// previously-flaky tests) in the case of
   216  			// socket-late-binding races from the http Client
   217  			// dialing this server and then getting an idle
   218  			// connection before the dial completed. There is thus
   219  			// a connected connection in StateNew with no
   220  			// associated Request. We only close StateIdle and
   221  			// StateNew because they're not doing anything. It's
   222  			// possible StateNew is about to do something in a few
   223  			// milliseconds, but a previous CL to check again in a
   224  			// few milliseconds wasn't liked (early versions of
   225  			// https://golang.org/cl/15151) so now we just
   226  			// forcefully close StateNew. The docs for Server.Close say
   227  			// we wait for "outstanding requests", so we don't close things
   228  			// in StateActive.
   229  			if st == http.StateIdle || st == http.StateNew {
   230  				s.closeConn(c)
   231  			}
   232  		}
   233  		// If this server doesn't shut down in 5 seconds, tell the user why.
   234  		t := time.AfterFunc(5*time.Second, s.logCloseHangDebugInfo)
   235  		defer t.Stop()
   236  	}
   237  	s.mu.Unlock()
   238  
   239  	// Not part of httptest.Server's correctness, but assume most
   240  	// users of httptest.Server will be using the standard
   241  	// transport, so help them out and close any idle connections for them.
   242  	if t, ok := http.DefaultTransport.(closeIdleTransport); ok {
   243  		t.CloseIdleConnections()
   244  	}
   245  
   246  	// Also close the client idle connections.
   247  	if s.client != nil {
   248  		if t, ok := s.client.Transport.(closeIdleTransport); ok {
   249  			t.CloseIdleConnections()
   250  		}
   251  	}
   252  
   253  	s.wg.Wait()
   254  }
   255  
   256  func (s *Server) logCloseHangDebugInfo() {
   257  	s.mu.Lock()
   258  	defer s.mu.Unlock()
   259  	var buf strings.Builder
   260  	buf.WriteString("httptest.Server blocked in Close after 5 seconds, waiting for connections:\n")
   261  	for c, st := range s.conns {
   262  		_, _ = fmt.Fprintf(&buf, "  %T %p %v in state %v\n", c, c, c.RemoteAddr(), st)
   263  	}
   264  	log.Print(buf.String())
   265  }
   266  
   267  // CloseClientConnections closes any open HTTP connections to the test Server.
   268  func (s *Server) CloseClientConnections() {
   269  	s.mu.Lock()
   270  	nconn := len(s.conns)
   271  	ch := make(chan struct{}, nconn)
   272  	for c := range s.conns {
   273  		go s.closeConnChan(c, ch)
   274  	}
   275  	s.mu.Unlock()
   276  
   277  	// Wait for outstanding closes to finish.
   278  	//
   279  	// Out of paranoia for making a late change in Go 1.6, we
   280  	// bound how long this can wait, since golang.org/issue/14291
   281  	// isn't fully understood yet. At least this should only be used
   282  	// in tests.
   283  	timer := time.NewTimer(5 * time.Second)
   284  	defer timer.Stop()
   285  	for i := 0; i < nconn; i++ {
   286  		select {
   287  		case <-ch:
   288  		case <-timer.C:
   289  			// Too slow. Give up.
   290  			return
   291  		}
   292  	}
   293  }
   294  
   295  // Certificate returns the certificate used by the server, or nil if
   296  // the server doesn't use TLS.
   297  func (s *Server) Certificate() *x509.Certificate {
   298  	return s.certificate
   299  }
   300  
   301  // Client returns an HTTP client configured for making requests to the server.
   302  // It is configured to trust the server's TLS test certificate and will
   303  // close its idle connections on Server.Close.
   304  func (s *Server) Client() *http.Client {
   305  	return s.client
   306  }
   307  
   308  func (s *Server) goServe() {
   309  	s.wg.Add(1)
   310  	go func() {
   311  		defer s.wg.Done()
   312  		_ = s.Config.Serve(s.Listener)
   313  	}()
   314  }
   315  
   316  // wrap installs the connection state-tracking hook to know which
   317  // connections are idle.
   318  func (s *Server) wrap() {
   319  	oldHook := s.Config.ConnState
   320  	s.Config.ConnState = func(c net.Conn, cs http.ConnState) {
   321  		s.mu.Lock()
   322  		defer s.mu.Unlock()
   323  
   324  		// Keep Close from returning until the user's ConnState hook
   325  		// (if any) finishes. Without this, the call to forgetConn
   326  		// below might send the count to 0 before we run the hook.
   327  		s.wg.Add(1)
   328  		defer s.wg.Done()
   329  
   330  		switch cs {
   331  		case http.StateNew:
   332  			s.wg.Add(1)
   333  			if _, exists := s.conns[c]; exists {
   334  				panic("invalid state transition")
   335  			}
   336  			if s.conns == nil {
   337  				s.conns = make(map[net.Conn]http.ConnState)
   338  			}
   339  			s.conns[c] = cs
   340  			if s.closed {
   341  				// Probably just a socket-late-binding dial from
   342  				// the default transport that lost the race (and
   343  				// thus this connection is now idle and will
   344  				// never be used).
   345  				s.closeConn(c)
   346  			}
   347  		case http.StateActive:
   348  			if oldState, ok := s.conns[c]; ok {
   349  				if oldState != http.StateNew && oldState != http.StateIdle {
   350  					panic("invalid state transition")
   351  				}
   352  				s.conns[c] = cs
   353  			}
   354  		case http.StateIdle:
   355  			if oldState, ok := s.conns[c]; ok {
   356  				if oldState != http.StateActive {
   357  					panic("invalid state transition")
   358  				}
   359  				s.conns[c] = cs
   360  			}
   361  			if s.closed {
   362  				s.closeConn(c)
   363  			}
   364  		case http.StateHijacked, http.StateClosed:
   365  			s.forgetConn(c)
   366  		}
   367  		if oldHook != nil {
   368  			oldHook(c, cs)
   369  		}
   370  	}
   371  }
   372  
   373  // closeConn closes c.
   374  // s.mu must be held.
   375  func (s *Server) closeConn(c net.Conn) { s.closeConnChan(c, nil) }
   376  
   377  // closeConnChan is like closeConn, but takes an optional channel to receive a value
   378  // when the goroutine closing c is done.
   379  func (s *Server) closeConnChan(c net.Conn, done chan<- struct{}) {
   380  	_ = c.Close()
   381  	if done != nil {
   382  		done <- struct{}{}
   383  	}
   384  }
   385  
   386  // forgetConn removes c from the set of tracked conns and decrements it from the
   387  // waitgroup, unless it was previously removed.
   388  // s.mu must be held.
   389  func (s *Server) forgetConn(c net.Conn) {
   390  	if _, ok := s.conns[c]; ok {
   391  		delete(s.conns, c)
   392  		s.wg.Done()
   393  	}
   394  }