Skip to content

Instantly share code, notes, and snippets.

@s-macke
Last active September 16, 2022 11:22
Show Gist options
  • Save s-macke/c3b1d0029ef61efc7ed2d22a4132cad2 to your computer and use it in GitHub Desktop.
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.
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