Skip to content

Instantly share code, notes, and snippets.

@mstrYoda
Created September 11, 2022 16:49
Show Gist options
  • Save mstrYoda/ecba8e844d3c0905e0afc7d0f10c6a35 to your computer and use it in GitHub Desktop.
Save mstrYoda/ecba8e844d3c0905e0afc7d0f10c6a35 to your computer and use it in GitHub Desktop.
func TestHttpServer(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("OK"))
})
srv := httptest.NewUnstartedServer(mux)
srv.Start()
time.Sleep(1 * time.Second)
resp, _ := http.Get(fmt.Sprintf("http://%s/test", srv.Listener.Addr().String()))
respBody, _ := io.ReadAll(resp.Body)
assert.Equal(t, string(respBody), "OK")
}
func TestHttpServerInMemory(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("OK"))
})
srv := httptest.NewUnstartedServer(mux)
ln := fasthttputil.NewInmemoryListener()
srv.Listener = ln
srv.Start()
c := http.Client{
Transport: &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return ln.Dial()
},
},
}
resp, _ := c.Get("http://localhost/test")
respBody, _ := io.ReadAll(resp.Body)
assert.Equal(t, string(respBody), "OK")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment