2024-02-08 00:41:17 +01:00
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"net/http/httputil"
|
|
|
|
"net/url"
|
|
|
|
"os"
|
|
|
|
"regexp"
|
|
|
|
"strconv"
|
|
|
|
|
2024-02-10 15:18:27 +01:00
|
|
|
"github.com/discord/lilliput"
|
2024-02-08 00:41:17 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
// read config file and parse it
|
|
|
|
confB, err := os.ReadFile("config.json")
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("reading config.json: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
hn := &Handler{}
|
|
|
|
err = json.Unmarshal(confB, hn)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("unmarshaling config.json: %v", err)
|
|
|
|
}
|
|
|
|
|
2024-02-10 15:18:27 +01:00
|
|
|
// create image ops object
|
|
|
|
hn.imageOps = lilliput.NewImageOps(512)
|
|
|
|
|
2024-02-08 00:41:17 +01:00
|
|
|
// Construct reverse proxy for bare/default size images
|
|
|
|
proxyURL, err := url.Parse(hn.ProxyTarget)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("parsing proxy_target as URL: %v", err)
|
|
|
|
}
|
|
|
|
hn.proxy = &httputil.ReverseProxy{
|
|
|
|
Rewrite: func(pr *httputil.ProxyRequest) {
|
|
|
|
pr.SetURL(proxyURL)
|
|
|
|
pr.Out.URL.RawQuery = ""
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
// compile patterns
|
|
|
|
for i, pattern := range hn.Patterns {
|
|
|
|
if len(pattern.Sizes) <= 1 {
|
|
|
|
log.Fatalf("pattern %d (%q) has too few possible sizes", i+1, pattern.Input)
|
|
|
|
}
|
|
|
|
|
|
|
|
hn.Patterns[i].regexp = regexp.MustCompile(pattern.Input)
|
|
|
|
}
|
|
|
|
|
|
|
|
// create directories for all image sizes
|
|
|
|
for _, pattern := range hn.Patterns {
|
|
|
|
for _, size := range pattern.Sizes {
|
|
|
|
err := os.Mkdir("cache/"+strconv.Itoa(size), 0o755)
|
|
|
|
if err != nil && !errors.Is(err, os.ErrExist) {
|
|
|
|
log.Fatalf("creating cache directory %q: %v", "cache/"+strconv.Itoa(size), err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Printf("serving on port %v", hn.Port)
|
|
|
|
|
|
|
|
err = http.ListenAndServe(":"+strconv.Itoa(hn.Port), hn)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("listening on port %v: %v", hn.Port, err)
|
|
|
|
}
|
|
|
|
}
|