github.com/rudderlabs/rudder-go-kit@v0.30.0/testhelper/httptest/httptest.go (about) 1 package httptest 2 3 import ( 4 "fmt" 5 "net" 6 "net/http" 7 nethttptest "net/http/httptest" 8 ) 9 10 // NewServer starts a new httptest server that listens on all interfaces, contrary to the standard net/httptest.Server that listens only on localhost. 11 // This is useful when you want to access the test http server from within a docker container. 12 func NewServer(handler http.Handler) *Server { 13 ts := NewUnStartedServer(handler) 14 ts.start() 15 return ts 16 } 17 18 // Server wraps net/httptest.Server to listen on all network interfaces 19 type Server struct { 20 *nethttptest.Server 21 } 22 23 func (s *Server) start() { 24 s.Server.Start() 25 _, port, err := net.SplitHostPort(s.Listener.Addr().String()) 26 if err != nil { 27 panic(fmt.Sprintf("httptest: failed to parse listener address: %v", err)) 28 } 29 s.URL = fmt.Sprintf("http://%s:%s", "localhost", port) 30 } 31 32 func NewUnStartedServer(handler http.Handler) *Server { 33 return &Server{&nethttptest.Server{ 34 Listener: newListener(), 35 Config: &http.Server{Handler: handler}, 36 }} 37 } 38 39 func newListener() net.Listener { 40 listener, tcpError := net.Listen("tcp", "0.0.0.0:0") 41 if tcpError == nil { 42 return listener 43 } 44 listener, tcp6Error := net.Listen("tcp6", "[::]:0") 45 if tcp6Error == nil { 46 return listener 47 } 48 panic(fmt.Sprintf("httptest: failed to start listener on a port for tcp (%v) and tcp6 (%v)", tcpError, tcp6Error)) 49 }