Last active
September 11, 2022 16:28
-
-
Save mstrYoda/201a3e959ae1719dfc49af46d89d92de to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func newLocalListener() net.Listener { | |
if serveFlag != "" { | |
l, err := net.Listen("tcp", serveFlag) | |
if err != nil { | |
panic(fmt.Sprintf("httptest: failed to listen on %v: %v", serveFlag, err)) | |
} | |
return l | |
} | |
l, err := net.Listen("tcp", "127.0.0.1:0") | |
if err != nil { | |
if l, err = net.Listen("tcp6", "[::1]:0"); err != nil { | |
panic(fmt.Sprintf("httptest: failed to listen on a port: %v", err)) | |
} | |
} | |
return l | |
} | |
func NewUnstartedServer(handler http.Handler) *Server { | |
return &Server{ | |
Listener: newLocalListener(), | |
Config: &http.Server{Handler: handler}, | |
} | |
} | |
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() | |
if serveFlag != "" { | |
fmt.Fprintln(os.Stderr, "httptest: serving on", s.URL) | |
select {} | |
} | |
} | |
func (s *Server) goServe() { | |
s.wg.Add(1) | |
go func() { | |
defer s.wg.Done() | |
s.Config.Serve(s.Listener) | |
}() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment