-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
103 lines (86 loc) · 2.32 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
package main
import (
"github.com/gin-gonic/gin"
"io"
"mime/multipart"
"net/http"
"net/url"
"os"
"path/filepath"
)
var (
host = os.Getenv("HOSTNAME")
expectedToken = os.Getenv("EXPECTED_TOKEN")
)
func main() {
router := gin.Default()
// Set a lower memory limit for multipart forms (default is 32 MiB)
router.MaxMultipartMemory = 8 << 20 // 8 MiB
if host == "" {
panic("HOSTNAME environment variable is not set") // Fail fast if the host is not set
}
if expectedToken == "" {
panic("EXPECTED_TOKEN environment variable is not set") // Fail fast if the token is not set
}
// Apply the token validation middleware globally
router.Use(tokenValidationMiddleware)
router.POST("/upload", uploadHandler)
err := router.Run(":8080")
if err != nil {
return
}
}
func uploadHandler(c *gin.Context) {
// Source
file, err := c.FormFile("file")
if err != nil {
c.String(http.StatusBadRequest, "ERR: get form err: %s", err.Error())
return
}
filename := filepath.Base(file.Filename)
ext := filepath.Ext(filename)
// Open the file
imageBytes, err := file.Open()
if err != nil {
c.String(http.StatusBadRequest, "ERR: unable to open file: %s", err.Error())
return
}
defer func(imageBytes multipart.File) {
err := imageBytes.Close()
if err != nil {
c.String(http.StatusBadRequest, "ERR: unable to close file: %s", err.Error())
}
}(imageBytes)
// Read the file content
fileContent, err := io.ReadAll(imageBytes)
if err != nil {
c.String(http.StatusBadRequest, "ERR: unable to read file: %s", err.Error())
return
}
if ext != ".webp" {
// Convert to webp
img, err := convertToWebP(fileContent)
if err != nil {
c.String(http.StatusBadRequest, "ERR: unable to convert to webp: %s", err.Error())
return
}
// Save webp
filename = filename[:len(filename)-len(ext)] + ".webp"
newFilename := wordGen() + ".webp"
if err := saveWebP(newFilename, img); err != nil {
c.String(http.StatusBadRequest, "ERR: unable to save webp: %s", err.Error())
return
}
} else {
// Save the original webp file
if err := c.SaveUploadedFile(file, filename); err != nil {
c.String(http.StatusBadRequest, "ERR: upload file err: %s", err.Error())
return
}
}
urlGen := url.URL{
Scheme: "https", Host: host,
Path: "/" + filename,
}
c.String(http.StatusOK, "SUCCESS: %s", urlGen.String())
}