Untitled
golang
2 months ago
1.1 kB
2
Indexable
Never
package main import ( "fmt" "math/rand" "net/http" "os" "time" ) func randomSleep() { const MAX_SLEEP_SECONDS = 5 n := rand.Intn(MAX_SLEEP_SECONDS) fmt.Printf("Merchant hook will respond in %ds\n", n) time.Sleep(time.Duration(n) * time.Second) } func randomHttpResponse() int { httpResponse := [2]int{http.StatusInternalServerError, http.StatusOK} return httpResponse[rand.Intn(2)] } func handleHook(w http.ResponseWriter, req *http.Request) { randomSleep() httpResponse := randomHttpResponse() w.WriteHeader(httpResponse) var responseMessage string if(httpResponse == http.StatusOK) { responseMessage = "✅ Hook succeeded" } else { responseMessage = "❌ Hook failed" } fmt.Fprintf(w, responseMessage) fmt.Println(responseMessage) } func getPort() string { port := os.Getenv("PORT") if(port == "") { return "8080" } return port } func main() { http.HandleFunc("/hooks", handleHook) port := getPort() fmt.Printf("🌎 Fake-merchant is listening on port %s", port) http.ListenAndServe(":" + port, nil) }