github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/builtins/core/httpclient/server_test.go (about) 1 package httpclient 2 3 import ( 4 "fmt" 5 "net/http" 6 "sync/atomic" 7 "testing" 8 "time" 9 ) 10 11 /* 12 This file creates a test HTTP server which just returns "$METHOD SUCCESSFUL" 13 (where $METHOD will be GET / POST / etc). 14 15 To instigate the server call `StartHTTPServer(t)` inside your testing func. 16 StartHTTPServer returns the address it is listening on - which will typically 17 be localhost and on a port number starting from 38001. Each instance of the 18 server will increment the port number. So you can run multiple tests (eg with 19 `-count n` flag) without worrying about shared server conflicts. 20 */ 21 22 var ( 23 testPort int32 = 38000 24 testHost = "localhost" 25 ) 26 27 type testHTTPHandler struct{} 28 29 func (h testHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { 30 _, err := w.Write([]byte(r.Method + " SUCCESSFUL")) 31 if err != nil { 32 panic(err) 33 } 34 } 35 36 func StartHTTPServer(t *testing.T) string { 37 for i := 0; i < 10; i++ { 38 var ( 39 port = atomic.AddInt32(&testPort, 1) 40 addr = fmt.Sprintf("%s:%d", testHost, port) 41 err = make(chan error) 42 ) 43 44 go func() { 45 err <- http.ListenAndServe(addr, testHTTPHandler{}) 46 }() 47 time.Sleep(100 * time.Millisecond) 48 select { 49 case <-err: 50 continue 51 default: 52 return addr 53 } 54 } 55 56 t.Errorf("Failed 10 times to dynamically allocate a port number") 57 return "" 58 }