From 14b07dfc7ec20df9d74bb69290571cf6fd2fe2fc Mon Sep 17 00:00:00 2001 From: Joe Tsai Date: Fri, 30 Jun 2017 14:10:48 -0700 Subject: net/http/httptest: allow creation of Server manually The Server struct has exported fields, which allows users to manually create a Server object without using using NewServer or NewTLSServer and directly call Start or StartTLS on their object. In order to ensure that manual creation of Server works, the NewUnstartedServer function should not initialize Server in any way that the user was not able to do themselves. For example, the setting of a unexported filed, client, is not something a user can do. Thus, rather than setting the client field in NewUnstartedServer, we lazily initialize it when Start or StartTLS is called. Otherwise, the Server logic can nil panic later when it assumes that this field has been initialized. Fixes #20871 Change-Id: I65c6a9f893ea963b0fbad0990b33af08007c1140 Reviewed-on: https://go-review.googlesource.com/47353 Reviewed-by: Brad Fitzpatrick --- src/net/http/httptest/server.go | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'src/net/http/httptest/server.go') diff --git a/src/net/http/httptest/server.go b/src/net/http/httptest/server.go index 1baec23d57..6075397a26 100644 --- a/src/net/http/httptest/server.go +++ b/src/net/http/httptest/server.go @@ -93,9 +93,6 @@ func NewUnstartedServer(handler http.Handler) *Server { return &Server{ Listener: newLocalListener(), Config: &http.Server{Handler: handler}, - client: &http.Client{ - Transport: &http.Transport{}, - }, } } @@ -104,6 +101,9 @@ func (s *Server) Start() { if s.URL != "" { panic("Server already started") } + if s.client == nil { + s.client = &http.Client{Transport: &http.Transport{}} + } s.URL = "http://" + s.Listener.Addr().String() s.wrap() s.goServe() @@ -118,6 +118,9 @@ func (s *Server) StartTLS() { if s.URL != "" { panic("Server already started") } + if s.client == nil { + s.client = &http.Client{Transport: &http.Transport{}} + } cert, err := tls.X509KeyPair(internal.LocalhostCert, internal.LocalhostKey) if err != nil { panic(fmt.Sprintf("httptest: NewTLSServer: %v", err)) -- cgit v1.3-5-g9baa