home/internal/static/repository/fs/fs_static.go

88 lines
1.9 KiB
Go

package fs
import (
"bytes"
"context"
"fmt"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"io"
"io/fs"
_ "golang.org/x/image/bmp"
_ "golang.org/x/image/webp"
"source.toby3d.me/toby3d/home/internal/domain"
"source.toby3d.me/toby3d/home/internal/static"
)
type fileServerStaticRepository struct {
root fs.FS
}
func NewFileServerStaticRepository(root fs.FS) static.Repository {
return &fileServerStaticRepository{
root: root,
}
}
func (repo *fileServerStaticRepository) Get(ctx context.Context, p string) (*domain.Static, error) {
info, err := fs.Stat(repo.root, p)
if err != nil {
return nil, fmt.Errorf("cannot stat static on path '%s': %w", p, err)
}
f, err := repo.root.Open(p)
if err != nil {
return nil, fmt.Errorf("cannot open static on path '%s': %w", p, err)
}
defer f.Close()
content, err := io.ReadAll(f)
if err != nil {
return nil, fmt.Errorf("cannot copy opened '%s' static contents into buffer: %w", p, err)
}
return domain.NewStatic(bytes.NewReader(content), info.ModTime(), info.Name()), nil
}
func (repo *fileServerStaticRepository) Fetch(ctx context.Context, pattern string) ([]*domain.Static, int, error) {
var (
err error
matches []string
)
if pattern != "" {
if matches, err = fs.Glob(repo.root, pattern); err != nil {
return nil, 0, fmt.Errorf("cannot match any static by pattern '%s': %w", pattern, err)
}
} else {
if err = fs.WalkDir(repo.root, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return fmt.Errorf("catched error while walk: %w", err)
}
if d.IsDir() {
return nil
}
matches = append(matches, path)
return nil
}); err != nil {
return nil, 0, fmt.Errorf("cannot walk through static directories: %w", err)
}
}
out := make([]*domain.Static, 0, len(matches))
for i := range matches {
if s, err := repo.Get(ctx, matches[i]); err == nil {
out = append(out, s)
}
}
return out, len(out), nil
}