Skip to content

Instantly share code, notes, and snippets.

@arbarlow
Created April 9, 2013 16:22
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 arbarlow/5347110 to your computer and use it in GitHub Desktop.
Save arbarlow/5347110 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"net/http"
"os"
"strings"
"strconv"
"github.com/Terry-Mao/paint"
"github.com/Terry-Mao/paint/wand"
)
func main() {
http.HandleFunc("/", handler)
fmt.Printf("Server ready\n")
http.ListenAndServe(":8080", nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
image_path := r.URL.Path[1:]
size_param := r.URL.Query().Get("size")
cached_img_name := createImageFileName(image_path, size_param)
exists, _ := fileExists(cached_img_name)
fmt.Printf("%v %v \n", cached_img_name, exists)
if !exists {
if(size_param != ""){
resizeImage(w, r, image_path, size_param)
} else {
http.ServeFile(w, r, cached_img_name)
}
} else {
// We know it doesnt exists, but this handles 404's well
http.ServeFile(w, r, cached_img_name)
}
}
func resizeImage(w http.ResponseWriter,
r *http.Request,
fileName, size_param string){
width, height := parseWidthHeight(size_param)
fmt.Printf("resizing to %d, %d \n", width, height)
wand.Genesis()
defer wand.Terminus()
magick := wand.NewMagickWand()
defer magick.Destroy()
err := magick.ReadImage(fileName);
check(w, err)
err = paint.Thumbnail(magick, uint(width), uint(height))
check(w, err)
cached_img_name := createImageFileName(fileName, size_param)
err = magick.WriteImage(cached_img_name)
check(w, err)
http.ServeFile(w, r, cached_img_name)
}
// exists returns whether the given file or directory exists or not
func fileExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil { return true, nil }
if os.IsNotExist(err) { return false, nil }
return false, err
}
func parseWidthHeight(s string) (int, int) {
width_height := strings.Split(s, "x")
width, _ := strconv.Atoi(width_height[0])
height, _ := strconv.Atoi(width_height[1])
return width, height
}
func createImageFileName(imageName, size string) string {
if size == "" {
return imageName
}
name_split := strings.Split(imageName, ".")
return name_split[0] + size + "." + name_split[1]
}
func check(w http.ResponseWriter, err error) {
if err != nil {
http.Error(w, err.Error(), 404)
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment