mirror of
https://github.com/NotAShelf/catApi.git
synced 2025-02-22 11:28:10 +00:00
better caching
This commit is contained in:
parent
05843107d6
commit
7d76753050
1 changed files with 56 additions and 11 deletions
67
main.go
67
main.go
|
@ -2,8 +2,8 @@ package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"flag"
|
|
||||||
"html/template"
|
"html/template"
|
||||||
|
"image"
|
||||||
"log"
|
"log"
|
||||||
"math/rand"
|
"math/rand"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
@ -20,6 +20,13 @@ var images []string
|
||||||
var logger = logrus.New()
|
var logger = logrus.New()
|
||||||
var port 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
|
// 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.
|
// way of displaying all images in a grid.
|
||||||
var tmpl = template.Must(template.New("index").Parse(`
|
var tmpl = template.Must(template.New("index").Parse(`
|
||||||
|
@ -78,13 +85,12 @@ func main() {
|
||||||
viper.SetConfigName("config") // name of config file (without extension)
|
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.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
|
viper.AddConfigPath(".") // path to look for the config file in
|
||||||
|
|
||||||
if err := viper.ReadInConfig(); err != nil {
|
if err := viper.ReadInConfig(); err != nil {
|
||||||
log.Fatalf("Error reading configuration file: %v", err)
|
log.Fatalf("Error reading configuration file: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
port = viper.GetString("server.port")
|
port = viper.GetString("server.port")
|
||||||
|
|
||||||
flag.Parse()
|
|
||||||
images = getImages()
|
images = getImages()
|
||||||
|
|
||||||
// Add request logging middleware
|
// Add request logging middleware
|
||||||
|
@ -104,6 +110,14 @@ func main() {
|
||||||
log.Fatal(http.ListenAndServe(":"+port, nil))
|
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 {
|
func getImages() []string {
|
||||||
files, err := os.ReadDir("images/")
|
files, err := os.ReadDir("images/")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -126,11 +140,12 @@ func homeHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "text/html")
|
w.Header().Set("Content-Type", "text/html")
|
||||||
tmpl.Execute(w, struct {
|
tmpl.Execute(w, struct {
|
||||||
Images []string
|
Images []string
|
||||||
}{Images: images})
|
}{Images: getCachedImages()})
|
||||||
}
|
}
|
||||||
|
|
||||||
func idHandler(w http.ResponseWriter, r *http.Request) {
|
func idHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
id := r.URL.Query().Get("id")
|
id := r.URL.Query().Get("id")
|
||||||
|
|
||||||
if id == "" {
|
if id == "" {
|
||||||
http.Error(w, "Missing id", http.StatusBadRequest)
|
http.Error(w, "Missing id", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
|
@ -159,11 +174,13 @@ func isValidImagePath(path string) bool {
|
||||||
}
|
}
|
||||||
|
|
||||||
func listHandler(w http.ResponseWriter, r *http.Request) {
|
func listHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
imageList := []map[string]string{}
|
imageList := []map[string]interface{}{}
|
||||||
for i := range images {
|
for i := range getCachedImages() {
|
||||||
imageInfo := map[string]string{
|
imageInfo := map[string]interface{}{
|
||||||
"id": strconv.Itoa(i),
|
"id": strconv.Itoa(i),
|
||||||
"url": "/api/id?id=" + strconv.Itoa(i),
|
"url": "/api/id?id=" + strconv.Itoa(i),
|
||||||
|
"filename": images[i],
|
||||||
|
"size": getImageSize("images/" + images[i]),
|
||||||
}
|
}
|
||||||
imageList = append(imageList, imageInfo)
|
imageList = append(imageList, imageInfo)
|
||||||
}
|
}
|
||||||
|
@ -178,6 +195,35 @@ func listHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Write(jsonData)
|
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 {
|
func logRequest(next http.Handler) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
|
@ -189,8 +235,7 @@ func logRequest(next http.Handler) http.Handler {
|
||||||
}
|
}
|
||||||
|
|
||||||
func randomHandler(w http.ResponseWriter, r *http.Request) {
|
func randomHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
source := rand.NewSource(time.Now().UnixNano())
|
rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||||
rand.New(source)
|
|
||||||
|
|
||||||
i := rand.Intn(len(images))
|
i := rand.Intn(len(images))
|
||||||
http.Redirect(w, r, "/api/id?id="+strconv.Itoa(i), http.StatusSeeOther)
|
http.Redirect(w, r, "/api/id?id="+strconv.Itoa(i), http.StatusSeeOther)
|
||||||
|
|
Loading…
Add table
Reference in a new issue