-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
256 lines (219 loc) · 6.26 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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package main
import (
"encoding/json"
"html/template"
"image"
"log"
"math/rand"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
var images []string
var logger = logrus.New()
var title string
var header string
var port string
// Cache for image list, it should expire every 10 minutes
// but until it does, images should load faster in the frontend.
var cachedImages struct {
images []string
expiry time.Time
}
// Okay I admit, this is bad. Just a workaround for now, until I figure out a clean
// way of displaying all images in a grid.
var tmpl = template.Must(template.New("index").Parse(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{.Title}}</title>
<style>
body { font-family: Arial, sans-serif; text-align: center; }
.gallery {
column-count: 5;
column-gap: 8px;
}
.gallery a {
display: inline-block;
width: 100%;
margin-bottom: 8px;
}
.gallery img {
width: 100%;
height: auto;
border-radius: 8px;
display: block;
}
@media (max-width: 1024px) { .gallery { column-count: 4; } }
@media (max-width: 768px) { .gallery { column-count: 3; } }
@media (max-width: 480px) { .gallery { column-count: 2; } }
</style>
</head>
<body>
<h1>{{.Header}}</h1>
<div class="gallery">
{{range $index, $img := .Images}}
<a href="/api/id?id={{$index}}">
<img src="/api/id?id={{$index}}" alt="Image {{$index}}">
</a>
{{end}}
</div>
</body>
</html>`))
func init() {
// Log as JSON instead of the default ASCII formatter
logger.SetFormatter(&logrus.JSONFormatter{})
// Output to stdout (or any other output you prefer)
logger.SetOutput(os.Stdout)
// Set the log level (info, warning, error, etc.)
logger.SetLevel(logrus.InfoLevel)
// Load config
viper.SetConfigName("config") // name of config file (without extension)
viper.SetConfigType("yaml") // REQUIRED if the config file does not have the extension in the name
viper.AddConfigPath(".") // path to look for the config file in
if err := viper.ReadInConfig(); err != nil {
log.Fatalf("Error reading configuration file: %v", err)
}
port = viper.GetString("server.port")
images = getImages()
// Load site settings (title and header)
title = viper.GetString("site.title")
header = viper.GetString("site.header")
}
func main() {
// Add request logging middleware
mux := http.NewServeMux()
mux.HandleFunc("/", homeHandler)
mux.HandleFunc("/api/id", idHandler)
mux.HandleFunc("/api/list", listHandler)
mux.HandleFunc("/api/random", randomHandler)
mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Invalid API path", http.StatusNotFound)
})
// Wrap the mux with the logging middleware
http.Handle("/", logRequest(mux))
log.Println("Server started at port", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}
func getCachedImages() []string {
if time.Now().After(cachedImages.expiry) {
cachedImages.images = getImages()
cachedImages.expiry = time.Now().Add(10 * time.Minute)
}
return cachedImages.images
}
func getImages() []string {
files, err := os.ReadDir("images/")
if err != nil {
logger.WithError(err).Fatal("Error reading images directory")
}
if len(files) == 0 {
logger.Warn("No images found in the images directory")
}
var images []string
for _, file := range files {
images = append(images, file.Name())
logger.Info("Loaded image:", file.Name())
}
return images
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
tmpl.Execute(w, struct {
Title string
Header string
Images []string
}{
Title: title,
Header: header,
Images: getCachedImages(),
})
}
func idHandler(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("id")
if id == "" {
http.Error(w, "Missing id", http.StatusBadRequest)
return
}
i, err := strconv.Atoi(id)
if err != nil || i < 0 || i >= len(images) {
http.Error(w, "Invalid id", http.StatusBadRequest)
return
}
imagePath := "images/" + images[i]
if !isValidImagePath(imagePath) {
http.Error(w, "Invalid image path", http.StatusBadRequest)
return
}
http.ServeFile(w, r, imagePath)
}
func isValidImagePath(path string) bool {
if !strings.HasPrefix(path, "images/") {
return false
}
return true
}
func listHandler(w http.ResponseWriter, r *http.Request) {
imageList := []map[string]interface{}{}
for i := range getCachedImages() {
imageInfo := map[string]interface{}{
"id": strconv.Itoa(i),
"url": "/api/id?id=" + strconv.Itoa(i),
"filename": images[i],
"size": getImageSize("images/" + images[i]),
}
imageList = append(imageList, imageInfo)
}
jsonData, err := json.Marshal(imageList)
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
}
func getImageSize(path string) map[string]interface{} {
file, err := os.Open(path)
if err != nil {
logger.WithError(err).Error("Error opening file for size")
return nil
}
defer file.Close()
// Decode image to get dimensions (JPEG/PNG only)
img, _, err := image.Decode(file)
if err != nil {
logger.WithError(err).Error("Error decoding image")
return nil
}
// Get file info for size
fileInfo, err := file.Stat()
if err != nil {
logger.WithError(err).Error("Error getting file info")
return nil
}
return map[string]interface{}{
"width": img.Bounds().Dx(),
"height": img.Bounds().Dy(),
"size": fileInfo.Size(),
}
}
func logRequest(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
logger.Infof("Started %s %s", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
duration := time.Since(start)
logger.Infof("Completed %s %s in %v", r.Method, r.URL.Path, duration)
})
}
func randomHandler(w http.ResponseWriter, r *http.Request) {
rand.New(rand.NewSource(time.Now().UnixNano()))
i := rand.Intn(len(images))
http.Redirect(w, r, "/api/id?id="+strconv.Itoa(i), http.StatusSeeOther)
}