-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
208 lines (152 loc) · 4.27 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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
package main
import (
"encoding/json"
"fmt"
"image/png"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
"discorddungeons.me/imageserver/cache"
"discorddungeons.me/imageserver/iql"
"github.com/joho/godotenv"
)
const VERSION = "1.0.1"
type CacheConfig struct {
ENABLE_CACHE bool
CACHE_DIRECTORY string
}
var cacheConfig CacheConfig
var cacheInstance *cache.Cache
// Sends the data as a JSON string to a http response.
func sendJSON(w http.ResponseWriter, data map[string]interface{}, httpStatus int) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(httpStatus)
if _, ok := data["statusCode"]; !ok {
// No status code in the data
data["statusCode"] = httpStatus
}
resp, err := json.MarshalIndent(data, "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
fmt.Fprint(w, string(resp))
}
// Sends an error to the responseWriter w, with the httpStatus, and an optional message
func sendError(w http.ResponseWriter, httpStatus int, message string) {
data := make(map[string]interface{})
data["httpError"] = http.StatusText(httpStatus)
if len(message) != 0 {
data["error"] = message
}
sendJSON(w, data, httpStatus)
}
// Gets an environment variable by key, or fallbacks to the fallback if it's not defined.
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}
// Handles requests to the /status endpoint
func statusHandler(w http.ResponseWriter, req *http.Request) {
sendJSON(w, make(map[string]interface{}), 200)
}
// Handles requests to the / endpoint.
func handler(w http.ResponseWriter, req *http.Request) {
if req.Method != "GET" && req.Method != "POST" {
sendError(w, http.StatusMethodNotAllowed, "")
return
}
if req.Method == "GET" {
data := make(map[string]interface{})
data["version"] = VERSION
sendJSON(w, data, http.StatusOK)
return
}
body, err := ioutil.ReadAll(req.Body)
if err != nil {
sendError(w, http.StatusBadRequest, "Can't read body")
return
}
if cacheConfig.ENABLE_CACHE {
hash := cacheInstance.ComputeHash(body)
if cacheInstance.HasFile(hash + ".png") {
http.ServeFile(w, req, cacheConfig.CACHE_DIRECTORY+"/"+hash+".png")
return
}
}
runner := iql.NewIQLRunner()
res, err := runner.RunIQL(string(body))
if err != nil {
sendError(w, http.StatusBadRequest, err.Error())
return
}
i := 0
for _, img := range res {
if i > 0 {
continue
}
w.Header().Set("Content-Type", "image/png")
err := png.Encode(w, img)
if err != nil {
sendError(w, http.StatusBadRequest, "Can't return image")
return
}
if cacheConfig.ENABLE_CACHE {
hash := cacheInstance.ComputeHash(body)
err := cacheInstance.SavePngFile(hash+".png", img)
if err != nil {
fmt.Println("Can't save file to cache: " + err.Error())
}
}
i++
}
}
// Executes the program
func main() {
godotenv.Load()
// if err != nil {
// log.Fatal("Error loading .env file")
// }
enableCache := true
c, err := strconv.ParseBool(getEnv("ENABLE_CACHE", "true"))
if err == nil {
enableCache = c
}
cacheConfig = CacheConfig{
ENABLE_CACHE: enableCache,
CACHE_DIRECTORY: getEnv("CACHE_DIRECTORY", "cache"),
}
cacheInstance = cache.NewCache(cacheConfig.CACHE_DIRECTORY)
serverPort := getEnv("SERVER_PORT", "8080")
if !strings.HasPrefix(serverPort, ":") {
serverPort = fmt.Sprintf(":%s", serverPort)
}
http.HandleFunc("/", handler)
http.HandleFunc("/status", statusHandler)
go func() {
for {
time.Sleep(time.Second)
log.Println("[ImageServer] Checking if server's started")
resp, err := http.Get(fmt.Sprintf("http://localhost%s/status", serverPort))
if err != nil {
log.Println("Failed:", err)
continue
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Println("Not OK:", resp.StatusCode)
continue
}
// Reached this point: server is up and running.
break
}
log.Printf("[ImageServer] Listening on port %s", serverPort)
}()
log.Println("[ImageServer] Starting server...")
log.Fatal(http.ListenAndServe(serverPort, nil))
}