Skip to content

Instantly share code, notes, and snippets.

@hugows
Last active November 14, 2019 18:58
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 hugows/a95ffca703c8c038bc5382ea9fe9041f to your computer and use it in GitHub Desktop.
Save hugows/a95ffca703c8c038bc5382ea9fe9041f to your computer and use it in GitHub Desktop.
poop.go
package main
import (
"fmt"
"net/http"
"time"
)
type server struct {
conns int
}
func (s *server) log(h http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
s.conns++
h.ServeHTTP(w, r) // call original
s.conns--
fmt.Printf("Connections left: %d\n", s.conns)
}
}
func (s *server) poop() http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
t := time.NewTicker(1 * time.Second)
defer t.Stop()
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "no poop for you", http.StatusInternalServerError)
return
}
w.Header().Set("X-Content-Type-Options", "nosniff")
count := 0
for {
select {
case <-req.Context().Done():
return
case <-t.C:
fmt.Fprintf(w, "Chunk #%d\n", count)
count++
flusher.Flush()
}
}
}
}
func main() {
s := server{}
http.HandleFunc("/", s.log(s.poop()))
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment