Skip to content

Instantly share code, notes, and snippets.

@himanshub16
Created March 6, 2018 20:18
Show Gist options
  • Save himanshub16/98f7c00a39256d58de838394a55682ff to your computer and use it in GitHub Desktop.
Save himanshub16/98f7c00a39256d58de838394a55682ff to your computer and use it in GitHub Desktop.
Simple streaming API in Go
package main
import (
"compress/gzip"
"fmt"
"net/http"
"time"
)
func main() {
waitDur, _ := time.ParseDuration("2s")
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
flusher := w.(http.Flusher)
for i := 0; i < 10; i++ {
fmt.Fprintln(w, "Hello world", i+1, time.Now().Unix())
flusher.Flush()
fmt.Println("hello", i+1)
time.Sleep(waitDur)
}
})
http.HandleFunc("/gzip", func(w http.ResponseWriter, r *http.Request) {
gzw := gzip.NewWriter(w)
defer gzw.Close()
flusher := w.(http.Flusher)
for i := 0; i < 10; i++ {
gzw.Write([]byte(fmt.Sprintln("Hello gzip", i+1, time.Now().Unix())))
flusher.Flush()
fmt.Println("gzip", i+1)
time.Sleep(waitDur)
}
})
http.ListenAndServe(":8000", nil)
}
@himanshub16
Copy link
Author

streaming-api-2018-03-07_02 03 52

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment