Skip to content

Instantly share code, notes, and snippets.

@imjasonh
Created May 22, 2014 00:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save imjasonh/e1d970122caa5f2e4a6a to your computer and use it in GitHub Desktop.
Save imjasonh/e1d970122caa5f2e4a6a to your computer and use it in GitHub Desktop.
HTTP server that serves a randomly generated-on-the-fly GIF (using https://gist.github.com/ImJasonH/7b309a4af2d4e32a2649)
package main
import (
"image"
"image/color"
"image/color/palette"
"log"
"math/rand"
"net/http"
"time"
supergif "gist.github.com/7b309a4af2d4e32a2649.git"
)
func main() {
http.HandleFunc("/", serveRandomGIF)
log.Fatal(http.ListenAndServe(":8080", nil))
}
const width = 200
const height = 200
func serveRandomGIF(w http.ResponseWriter, r *http.Request) {
f, ok := w.(http.Flusher)
if !ok {
http.Error(w, "ResponseWriter does not support Flush", http.StatusBadRequest)
return
}
i, err := supergif.NewIncrementalEncoder(w, randomImage())
if err != nil {
log.Fatal(err)
}
log.Println("wrote first frame")
for {
f.Flush()
time.Sleep(5*time.Second)
if err := i.EncodeNext(randomImage()); err != nil {
log.Fatal(err)
}
log.Println("wrote frame")
}
}
func randomImage() *image.Paletted {
pm := image.NewPaletted(image.Rectangle{image.Point{0,0}, image.Point{width, height}}, palette.WebSafe)
pm.Set(rand.Intn(width), rand.Intn(height), color.White)
return pm
}
@andybons
Copy link

on line 26, instead of returning an error, just wrap the ResponseWriter in a bufio.NewWriter and you'll get Flush from that.

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