75 lines
1.7 KiB
Go
75 lines
1.7 KiB
Go
|
// SPDX-License-Identifier: Apache-2.0
|
||
|
package main
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"errors"
|
||
|
"log"
|
||
|
"net/http"
|
||
|
"net/http/httputil"
|
||
|
"net/url"
|
||
|
"os"
|
||
|
"regexp"
|
||
|
"strconv"
|
||
|
|
||
|
"github.com/davidbyttow/govips/v2/vips"
|
||
|
)
|
||
|
|
||
|
func main() {
|
||
|
// set vips log level to WARN, else it will spam logs on info level
|
||
|
vips.LoggingSettings(nil, vips.LogLevelWarning)
|
||
|
|
||
|
vips.Startup(nil)
|
||
|
defer vips.Shutdown()
|
||
|
|
||
|
// 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)
|
||
|
}
|
||
|
|
||
|
// 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)
|
||
|
}
|
||
|
}
|