Skip to content

Instantly share code, notes, and snippets.

@lucatironi
Created July 26, 2016 06:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucatironi/038dc7356b72d75b705ef8c6f19052e2 to your computer and use it in GitHub Desktop.
Save lucatironi/038dc7356b72d75b705ef8c6f19052e2 to your computer and use it in GitHub Desktop.
Image placeholder microservice
package main
import (
"bytes"
"fmt"
"image"
"image/color"
"image/draw"
"image/jpeg"
"log"
"net/http"
"strconv"
"time"
"golang.org/x/image/font"
"golang.org/x/image/font/inconsolata"
"golang.org/x/image/math/fixed"
)
func Logger(inner http.HandlerFunc, name string) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
inner.ServeHTTP(w, r)
log.Printf(
"%s\t%s\t%s\t%s",
r.Method,
r.RequestURI,
name,
time.Since(start),
)
})
}
func addLabel(img *image.RGBA, x, y int, label string) {
col := color.RGBA{64, 64, 64, 255}
d := &font.Drawer{
Dst: img,
Src: image.NewUniform(col),
Face: inconsolata.Bold8x16,
}
l := d.MeasureString(label)
d.Dot = fixed.P(x - int(l) / 128, y)
d.DrawString(label)
}
func ImagePlaceholderHandler(w http.ResponseWriter, r *http.Request) {
width, err := strconv.Atoi(r.FormValue("w"))
if err != nil {
width = 512
}
height, err := strconv.Atoi(r.FormValue("h"))
if err != nil {
height = 512
}
m := image.NewRGBA(image.Rect(0, 0, width, height))
grey := color.RGBA{200, 200, 200, 255}
draw.Draw(m, m.Bounds(), &image.Uniform{grey}, image.ZP, draw.Src)
addLabel(m, width/2, height/2, fmt.Sprintf("%v x %v", width, height))
var img image.Image = m
buffer := new(bytes.Buffer)
if err := jpeg.Encode(buffer, img, nil); err != nil {
log.Println("unable to encode image.")
}
w.Header().Set("Content-Type", "image/jpeg")
w.Header().Set("Content-Length", strconv.Itoa(len(buffer.Bytes())))
w.WriteHeader(http.StatusOK)
if _, err := w.Write(buffer.Bytes()); err != nil {
log.Println("unable to write image.")
}
}
func main() {
http.HandleFunc("/", Logger(ImagePlaceholderHandler, "image#placeholder"))
log.Printf("Service listening on port 8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment