Serving server generated PNGs over HTTP in golang

Building on the PNG generation code. We can easily expand this to serve the content over HTTP.

The following example will serve content from the filesystem for everything but “/images”. This path will generate and send a random 100×100 PNG to the client.

package main

import (
    "github.com/daaku/go.httpgzip"
    "net/http"
    "image"
    "image/png"
    "image/color"
    "math/rand"
)

func handler(w http.ResponseWriter, r *http.Request) {
  myimage := image.NewRGBA(image.Rectangle{image.Point{0,0},image.Point{100,100}})

  // This loop just fills the image with random data
  for x := 0; x < 100; x++ {
    for y := 0; y < 100; y++ {
      c := color.RGBA{uint8(rand.Intn(255)),uint8(rand.Intn(255)),uint8(rand.Intn(255)),255}
      myimage.Set(x,y,c)
    }
  }

  png.Encode(w, myimage)
}

func main() {
  http.HandleFunc("/images", handler)  
  http.Handle("/", httpgzip.NewHandler(http.FileServer(http.Dir("."))))

  http.ListenAndServe(":8080", nil)
}