Last active
November 14, 2019 18:58
-
-
Save hugows/a95ffca703c8c038bc5382ea9fe9041f to your computer and use it in GitHub Desktop.
poop.go
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
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