Skip to content

Instantly share code, notes, and snippets.

@mstrYoda
Created September 11, 2022 17:16
Show Gist options
  • Save mstrYoda/ff206996489c5c64fc3e8c7c1b74cd11 to your computer and use it in GitHub Desktop.
Save mstrYoda/ff206996489c5c64fc3e8c7c1b74cd11 to your computer and use it in GitHub Desktop.
type InMemListener struct {
connCh chan net.Conn
}
func newInMemListener() *InMemListener {
return &InMemListener{
connCh: make(chan net.Conn, 1),
}
}
func (i InMemListener) Accept() (net.Conn, error) {
return <-i.connCh, nil
}
func (i InMemListener) Close() error { return nil }
func (i InMemListener) Addr() net.Addr {
return &net.UnixAddr{
Name: "InMemListener",
Net: "memory",
}
}
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 := newInMemListener()
conn1, conn2 := net.Pipe()
ln.connCh <- conn2
srv.Listener = ln
srv.Start()
c := http.Client{
Transport: &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return conn1, nil
},
},
}
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