Created
May 22, 2014 00:55
-
-
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)
This file contains 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 ( | |
"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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
on line 26, instead of returning an error, just wrap the ResponseWriter in a bufio.NewWriter and you'll get Flush from that.