Skip to content

Instantly share code, notes, and snippets.

@gerep
Created March 8, 2019 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gerep/330c69389d11c3a5c910990c814bade6 to your computer and use it in GitHub Desktop.
Save gerep/330c69389d11c3a5c910990c814bade6 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"log"
"math/rand"
"net/http"
"time"
)
type tonto struct {
repeat int
message string
code int
sleep time.Duration
}
var messages = []string{
"OK",
"Unauthorized",
"Bad request",
"Not found",
"Internal error",
}
var codes = []int{
200,
401,
400,
404,
500,
}
var t tonto
func tontonator() tonto {
magic := rand.Intn(220)
fmt.Println("Magic:", magic)
repeat := rand.Intn(6)
fmt.Println("Repeat:", repeat)
switch {
default:
return tonto{
repeat: repeat,
message: messages[0],
code: codes[0],
}
case magic > 125 && magic <= 150:
return tonto{
repeat: repeat,
message: messages[1],
code: codes[1],
}
case magic > 150 && magic <= 175:
return tonto{
repeat: repeat,
message: messages[2],
code: codes[2],
}
case magic > 175 && magic <= 185:
return tonto{
repeat: repeat,
message: messages[3],
code: codes[3],
}
case magic > 185 && magic <= 200:
return tonto{
repeat: repeat,
message: messages[4],
code: codes[4],
}
case magic > 200 && magic <= 220:
return tonto{
repeat: repeat,
message: "",
code: 0,
sleep: 60 * time.Second,
}
}
}
func handle(w http.ResponseWriter, r *http.Request) {
if t.repeat > 0 {
fmt.Printf("> Existing tonto:\n%#v\n", t)
t.repeat--
w.WriteHeader(t.code)
w.Write([]byte(t.message))
return
}
t = tontonator()
if t.sleep > 0 {
fmt.Println("Sleeping for", t.sleep)
time.Sleep(t.sleep)
}
fmt.Printf("- New tonto:\n%#v\n", t)
w.WriteHeader(t.code)
w.Write([]byte(t.message))
t.repeat--
}
func main() {
rand.Seed(time.Now().UTC().UnixNano())
http.HandleFunc("/", handle)
t = tonto{
repeat: 1,
message: "OK",
code: 200,
}
fmt.Println("Listening on 8080...")
log.Fatal(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment