Last active
October 27, 2020 19:33
-
-
Save 0xc0d/2601fab1e0ec9bb35e7e87247b016cbc to your computer and use it in GitHub Desktop.
simple buggy http server
This file contains hidden or 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
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