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