Created
April 9, 2013 16:22
-
-
Save arbarlow/5347110 to your computer and use it in GitHub Desktop.
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 ( | |
"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