Skip to content

Instantly share code, notes, and snippets.

@0xc0d
Last active October 27, 2020 19:33
Show Gist options
  • Save 0xc0d/2601fab1e0ec9bb35e7e87247b016cbc to your computer and use it in GitHub Desktop.
Save 0xc0d/2601fab1e0ec9bb35e7e87247b016cbc to your computer and use it in GitHub Desktop.
simple buggy http server
import (
"encoding/json"
"math/rand"
"net/http"
_ "net/http/pprof"
"time"
)
func main() {
http.HandleFunc("/log", logHandler)
http.ListenAndServe(":8080", nil)
}
func logHandler(w http.ResponseWriter, r *http.Request) {
ch := make(chan int)
go func() {
obj := make(map[string]float64)
if err := json.NewDecoder(r.Body).Decode(&obj); err != nil {
ch <- http.StatusBadRequest
return
}
// simulation of a time consuming process like writing logs into db
time.Sleep(time.Duration(rand.Intn(400)) * time.Millisecond)
ch <- http.StatusOK
}()
select {
case status := <-ch:
w.WriteHeader(status)
case <-time.After(200 * time.Millisecond):
w.WriteHeader(http.StatusRequestTimeout)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment