github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/test/count/server/handler.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "io" 6 "net/http" 7 "os" 8 "strconv" 9 "sync/atomic" 10 ) 11 12 var ( 13 counter int32 14 response = []byte{'O', 'K'} 15 ) 16 17 type testHTTPHandler struct{} 18 19 func (h testHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { 20 switch r.RequestURI { 21 case "/count": 22 count(w, r) 23 return 24 25 case "/t": 26 total(w, false) 27 28 case "/total": 29 total(w, true) 30 31 default: 32 fmt.Fprintf(os.Stderr, "Invalid path: %s\n", r.RequestURI) 33 os.Exit(1) 34 } 35 } 36 37 func count(w http.ResponseWriter, r *http.Request) { 38 b, err := io.ReadAll(r.Body) 39 if err != nil { 40 fmt.Fprintf(os.Stderr, "Error reading count: %s\n", err) 41 } 42 43 i, err := strconv.Atoi(string(b)) 44 if err != nil { 45 fmt.Fprintf(os.Stderr, "Error reading count: %s\n", err) 46 } 47 48 atomic.AddInt32(&counter, int32(i)) 49 50 _, err = w.Write(response) 51 if err != nil { 52 fmt.Fprintf(os.Stderr, "Error writing response: %s\n", err) 53 } 54 } 55 56 func total(w http.ResponseWriter, human bool) { 57 i := atomic.LoadInt32(&counter) 58 s := strconv.Itoa(int(i)) 59 if human { 60 s += " tests ran\n" 61 } 62 63 _, err := w.Write([]byte(s)) 64 if err != nil { 65 fmt.Fprintf(os.Stderr, "Error writing response: %s\n", err) 66 } 67 68 exit <- true 69 }