-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
executable file
·166 lines (130 loc) · 3.7 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
package main
import (
_ "embed"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"image"
"image/draw"
"image/math/f64"
"image/jpeg"
)
//go:embed index.tmpl.html
var indexTmplRaw string
var indexTmpl *template.Template
func main() {
// Support for auto-deploy .zephyr stuff
port := os.Getenv("PORT")
if port == "" {
port = "9876"
}
var err error
indexTmpl, err = template.New("index.html").Parse(indexTmplRaw)
if err != nil {
log.Fatal(err)
}
// HTTP Request handlers
http.HandleFunc("/", rootHandler)
http.HandleFunc("/photos/", photoHandler)
http.HandleFunc("/static/", staticHandler)
http.HandleFunc("/upload", uploadHandler)
fmt.Println("Listening on port", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}
func rootHandler(w http.ResponseWriter, req *http.Request) {
files, err := ioutil.ReadDir("./db/")
if err != nil {
fmt.Fprintln(os.Stderr, "request to /, error:", err)
http.Error(w, "error getting photos from db", 500)
return
}
photoURLs := []string{}
for _, file := range files {
if file.Name() == "README.md" || file.Name() == ".gitignore" {
continue
}
photoURLs = append(photoURLs, "/photos/"+file.Name())
}
sort.Strings(photoURLs)
sort.Sort(sort.Reverse(sort.StringSlice(photoURLs)))
data := struct {
Photos []string
}{
Photos: photoURLs,
}
if err := indexTmpl.Execute(w, data); err != nil {
fmt.Fprintln(os.Stderr, "error executing index.html template:", err)
}
}
func photoHandler(w http.ResponseWriter, req *http.Request) {
fileName := strings.Replace(req.URL.Path, "/photos/", "", 1)
file, err := os.Open("./db/" + fileName)
if err != nil {
http.Error(w, "error opening photo: "+err.Error(), http.StatusUnprocessableEntity)
return
}
defer file.Close()
io.Copy(w, file)
}
func staticHandler(w http.ResponseWriter, req *http.Request) {
fileName := strings.Replace(req.URL.Path, "/static/", "", 1)
file, err := os.Open("./static/" + fileName)
if err != nil {
http.Error(w, "error opening photo: "+err.Error(), http.StatusUnprocessableEntity)
return
}
defer file.Close()
w.Header().Set("Content-Type", "text/css")
io.Copy(w, file)
}
// Handler for uploads
func uploadHandler(w http.ResponseWriter, req *http.Request) {
fmt.Println("upload endpoint hit by", req.RemoteAddr)
req.ParseMultipartForm(10 << 20) // 10mb file limit
// Recieved data from the html upload form
photo, handler, err := req.FormFile("photo")
if err != nil {
http.Error(w, "error receiving uploaded photo: "+err.Error(), http.StatusUnprocessableEntity)
return
}
defer photo.Close()
// Verify that it is, in fact, a photo
ext := strings.ToLower(filepath.Ext(handler.Filename))
if ext != ".png" && ext != ".jpeg" && ext != ".jpg" {
http.Error(w, "must be a png or jpeg", http.StatusUnprocessableEntity)
return
}
unixTime := strconv.FormatInt(time.Now().Unix(), 10)
file, err := os.Open("db/upload-"+unixTime+ext)
if err != nil {
http.Error(w, "internal error storing file: "+err.Error(), 500)
return
}
defer file.Close()
io.Copy(file, photo)
// resize image and store smaller size
compressedFile, err := os.Open("db/upload-"+unixTime+"_compressed"+ext)
if err != nil {
http.Error(w, "internal error storing file: "+err.Error(), 500)
return
}
defer compressedFile.Close()
src, _, err := image.Decode(photo)
if err != nil {
http.Error(w, "internal error resizing photo: "+err.Error(), 500)
}
scalingFactor := src.Bounds().Max.X / 512
dst := image.NewRGBA(image.Rect(0, 0, 512, src.Bounds().Max.Y * scalingFactor))
draw.ApproxBiLinear.Scale(dst, dst.Rect, src, src.Bounds(), draw.Over, nil)
jpeg.Encode(compressedFile, dst)
http.Redirect(w, req, "/", http.StatusFound)
}