This repository has been archived by the owner on Sep 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
94 lines (78 loc) · 2.43 KB
/
server.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
package main
import (
"bytes"
"fmt"
"io"
"log"
"net/http"
"os"
)
const TMP_FILE_DIRECTORY = "./tmp/uploads"
const COMPRESSED_QUALITY = 40
func homeHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Error(w, "404 not found.", http.StatusNotFound)
return
}
fmt.Fprintf(w, "Welcome to Shrimpify!\n\nTo use me, simply send a POST request with an \"image\" field containing a JPEG or PNG image and we will compress it for you.")
}
func shrinkHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/shrink" {
http.Error(w, "404 not found.", http.StatusNotFound)
return
}
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
err := r.ParseMultipartForm(32 << 20) // 32 MB
if err != nil {
http.Error(
w,
"The uploaded image is too big. Please choose an image that is less than 32MB in size.",
http.StatusBadRequest,
)
return
}
file, h, err := r.FormFile("image")
if err != nil {
http.Error(w, "There was a problem with your image.", http.StatusBadRequest)
return
}
imageBuffer := bytes.NewBuffer(nil)
if _, err := io.Copy(imageBuffer, file); err != nil {
http.Error(w, "An internal error occurred: "+err.Error(), http.StatusInternalServerError)
return
}
filetype := http.DetectContentType(imageBuffer.Bytes())
if filetype != "image/jpeg" && filetype != "image/png" {
http.Error(w, "The provided file format is not allowed. Please upload a JPEG or PNG image", http.StatusBadRequest)
return
}
err = os.MkdirAll(TMP_FILE_DIRECTORY, 0700)
if err != nil {
http.Error(w, "An internal error occurred: "+err.Error(), http.StatusInternalServerError)
return
}
processedImageBuffer, err := processImage(imageBuffer.Bytes(), COMPRESSED_QUALITY)
if err != nil {
http.Error(w, "An internal error occurred: "+err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "image/webp")
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(processedImageBuffer)))
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"converted-%s\"", h.Filename))
w.Write(processedImageBuffer)
}
func main() {
port := os.Getenv("PORT")
if port == "" {
log.Fatal("$PORT must be set")
}
http.HandleFunc("/", homeHandler)
http.HandleFunc("/shrink", shrinkHandler)
fmt.Printf("Starting server on port %s\n", port)
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Fatal(err)
}
}