-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
126 lines (102 loc) · 2.58 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
package main
import (
"bytes"
"errors"
"fmt"
"os"
"strconv"
"sync"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
_ "golang.org/x/image/webp"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/compress"
"github.com/kolesa-team/go-webp/encoder"
"github.com/kolesa-team/go-webp/webp"
)
func main() {
var supportedLock sync.Mutex
supported := supported()
key := getKey()
if key == "" {
fmt.Println("No $KEY set, this is required for the authentication")
os.Exit(1)
}
fmt.Println("Bearer access key:", key)
app := fiber.New()
app.Use(compress.New())
app.Get("", func(c *fiber.Ctx) error {
return c.JSON(map[string]interface{}{"status": "ok"})
})
app.Post("/api/preview", requireAuth(), func(c *fiber.Ctx) error {
file, err := c.FormFile("document")
if err != nil {
return err
}
height, err := reqFormSizeField(c, "height")
if err != nil {
return err
}
width, err := reqFormSizeField(c, "width")
if err != nil {
return err
}
contentType := file.Header.Get("Content-Type")
if len(contentType) == 0 {
return errors.New("file content type missing")
}
serverFile, err := file.Open()
if err != nil {
return errors.New("unable to read form file")
}
supportedLock.Lock()
supportedCopy := supported
supportedLock.Unlock()
img, cropAlignTop, err := formFileToImage(serverFile, contentType, supportedCopy)
if err != nil {
return err
}
img = resizeAndCrop(img, height, width, cropAlignTop)
options, err := encoder.NewLossyEncoderOptions(encoder.PresetDefault, 50)
if err != nil {
return errors.New("unable to create response")
}
resBuf := bytes.NewBuffer(nil)
err = webp.Encode(resBuf, img, options)
if err != nil {
return errors.New("unable to crop file")
}
c.Response().Header.Set("Content-Type", "image/webp")
c.Write(resBuf.Bytes())
return nil
})
port := ":3030"
envPort := os.Getenv("PORT")
if len(envPort) > 0 {
port = ":" + envPort
}
app.Listen(port)
}
func reqFormSizeField(c *fiber.Ctx, field string) (int, error) {
fieldVal := c.FormValue(field)
if len(fieldVal) == 0 {
return 0, fmt.Errorf("size property %s not set", field)
}
res64, err := strconv.ParseInt(fieldVal, 10, 64)
if err != nil {
return 0, fmt.Errorf("size property %s not a number", field)
}
res := int(res64)
if res > 10_000 {
return 0, fmt.Errorf("size property %s cannot be greater than 10_000", field)
}
if res < 0 {
return 0, fmt.Errorf("size property %s cannot be less than 0", field)
}
res = res / 20 * 20 // Round the value to steps of 20
if res == 0 {
res = 20
}
return res, nil
}