caching icons automatically

This commit is contained in:
Hazel Noack 2025-07-15 13:08:23 +02:00
parent e627d02d08
commit 808ce89dfc
4 changed files with 95 additions and 4 deletions

View File

@ -136,3 +136,12 @@ func (rc *Config) LoadConfigFile(file string) error {
return toml.Unmarshal(content, rc)
}
func (c *Config) Init() error {
for i, w := range c.Template.Websites {
c.Template.Websites[i].Cache()
fmt.Println(w.ImageUrl)
}
return nil
}

View File

@ -1,7 +1,76 @@
package rendering
import (
"crypto/sha1"
"encoding/hex"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
)
type Website struct {
Url string
Name string
ImageUrl string
Url string
Name string
ImageUrl string
IsFetched bool
}
const CacheUrl = "cache"
func GetCacheDir() (string, error) {
baseDir, err := os.UserCacheDir()
if err != nil {
return "", err
}
cacheDir := filepath.Join(baseDir, "startpage")
err = os.MkdirAll(cacheDir, 0o755)
if err != nil {
return "", err
}
return cacheDir, nil
}
func hashUrl(url string) string {
h := sha1.New()
io.WriteString(h, url)
return hex.EncodeToString(h.Sum(nil))
}
func (w *Website) Cache() error {
if w.IsFetched {
return nil
}
cacheDir, err := GetCacheDir()
if err != nil {
return err
}
filename := hashUrl(w.ImageUrl)
fmt.Println(w.ImageUrl + " => " + filename)
targetPath := filepath.Join(cacheDir, filename)
resp, err := http.Get(w.ImageUrl)
if err != nil {
return err
}
defer resp.Body.Close()
file, err := os.Create(targetPath)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(file, resp.Body)
if err != nil {
return err
}
w.ImageUrl, _ = url.JoinPath(CacheUrl, filename)
w.IsFetched = true
return nil
}

13
main.go
View File

@ -74,6 +74,11 @@ func main() {
fmt.Println(err)
}
err = CurrentConfig.Init()
if err != nil {
fmt.Println(err)
}
err = FetchDiyHrt()
if err != nil {
fmt.Println(err)
@ -81,6 +86,14 @@ func main() {
e := echo.New()
// statically serve the file
cacheDir, err := rendering.GetCacheDir()
if err == nil {
e.Static("/cache", cacheDir)
} else {
fmt.Println(err)
}
// https://echo.labstack.com/docs/cookbook/embed-resources
staticHandler := http.FileServer(getFileSystem())
e.GET("/assets/*", echo.WrapHandler(http.StripPrefix("/", staticHandler)))

View File

@ -1 +1 @@
exit status 1exit status 1
exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1