Last active
September 16, 2022 11:22
-
-
Save s-macke/c3b1d0029ef61efc7ed2d22a4132cad2 to your computer and use it in GitHub Desktop.
Sleep Server in Go. It just sleeps for a given time for any request. Useful for easy mock of backends.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"net/http" | |
"time" | |
) | |
var defaultSleepTimeMs *int | |
var defaultStatusCode *int | |
func SleepServer(w http.ResponseWriter, r *http.Request) { | |
sleep, err := time.ParseDuration(r.URL.Query().Get("sleep")) | |
if err != nil { | |
sleep = time.Duration(*defaultSleepTimeMs) * time.Millisecond | |
} | |
time.Sleep(sleep) | |
w.WriteHeader(*defaultStatusCode) | |
} | |
func main() { | |
port := flag.String("port", "8080", "port to serve on") | |
defaultSleepTimeMs = flag.Int("sleep", 1000, "default sleep time") | |
defaultStatusCode = flag.Int("status", 200, "default status code") | |
flag.Parse() | |
fmt.Printf("Starting server at port " + *port + "\n") | |
http.HandleFunc("/", SleepServer) | |
err := http.ListenAndServe(":"+*port, nil) | |
if err != nil { | |
fmt.Println(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment