🗃️ Created FileSystem static repository implementation

This commit is contained in:
Maxim Lebedev 2023-11-09 06:49:44 +06:00
parent 378ec02778
commit 6ae785ebc9
Signed by: toby3d
GPG Key ID: 1F14E25B7C119FC5
1 changed files with 72 additions and 0 deletions

View File

@ -0,0 +1,72 @@
package fs
import (
"context"
"fmt"
"io/fs"
"path/filepath"
"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.File, error) {
info, err := fs.Stat(repo.root, p)
if err != nil {
return nil, fmt.Errorf("cannot stat static on path '%s': %w", p, err)
}
content, err := fs.ReadFile(repo.root, p)
if err != nil {
return nil, fmt.Errorf("cannot read static content on path '%s': %w", p, err)
}
return &domain.File{
Path: p,
Updated: info.ModTime(),
Content: content,
}, nil
}
func (repo *fileServerStaticRepository) Fetch(ctx context.Context, d string) ([]*domain.File, int, error) {
entries, err := fs.ReadDir(repo.root, d)
if err != nil {
return nil, 0, fmt.Errorf("cannot read directory on path '%s': %w", d, err)
}
out := make([]*domain.File, 0, len(entries))
for _, entry := range entries {
if entry.IsDir() {
continue
}
content, err := fs.ReadFile(repo.root, filepath.Join(d, entry.Name()))
if err != nil {
continue
}
info, err := entry.Info()
if err != nil {
continue
}
out = append(out, &domain.File{
Path: filepath.Join(d, info.Name()),
Updated: info.ModTime(),
Content: content,
})
}
return out, len(out), nil
}