73 lines
1.5 KiB
Go
73 lines
1.5 KiB
Go
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
|
|
}
|