/
main.go
82 lines (66 loc) · 1.71 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
import(
"github.com/gographics/imagick/imagick"
"github.com/go-martini/martini"
"github.com/crowdmob/goamz/aws"
"github.com/crowdmob/goamz/s3"
"strings"
"strconv"
"net/http"
)
func main() {
m := martini.Classic()
m.Get("/**", GetResizedImage)
m.Run()
}
func GetResizedImage(params martini.Params, w http.ResponseWriter, r *http.Request) {
width, height, path := ParsePath(params["_1"])
bucket := GetBucket()
blob, err := bucket.Get(path)
if err != nil {
WriteNotFound(w)
return
}
image := Resize(uint(width), uint(height), blob)
w.Write(image)
}
// @args p [string] image/Bs3iSswCIAE075C.500x500.jpg
func ParsePath(p string) (int, int, string) {
path := strings.Split(p, "/")
name := path[len(path) - 1]
nameArr := strings.Split(name, ".")
sizeParam := nameArr[1]
width, height := ParseSizeParam(sizeParam)
fname := nameArr[0] + "." + nameArr[2]
path[len(path) - 1] = fname
imgPath := strings.Join(path, "/")
return width, height, imgPath
}
// @args p [string] 100x100
func ParseSizeParam(p string) (int, int) {
sizeArr := strings.Split(p, "x")
width, _ := strconv.Atoi(sizeArr[0])
height, _ := strconv.Atoi(sizeArr[1])
return width, height
}
func WriteNotFound(w http.ResponseWriter) {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("404"))
}
func GetBucket() *s3.Bucket {
auth, err := aws.EnvAuth()
if err != nil {
panic(err.Error())
}
s := s3.New(auth, aws.USEast)
return s.Bucket("filmapp-development")
}
func Resize(w, h uint, blob []byte) []byte {
imagick.Initialize()
defer imagick.Terminate()
wand := imagick.NewMagickWand()
defer wand.Destroy()
_ = wand.ReadImageBlob(blob)
wand.ResizeImage(w, h, imagick.FILTER_LANCZOS2_SHARP, 1)
return wand.GetImageBlob()
}