59 lines
1.2 KiB
Go
59 lines
1.2 KiB
Go
package usecase
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"path"
|
|
|
|
"golang.org/x/text/language"
|
|
|
|
"source.toby3d.me/toby3d/home/internal/domain"
|
|
"source.toby3d.me/toby3d/home/internal/page"
|
|
"source.toby3d.me/toby3d/home/internal/static"
|
|
"source.toby3d.me/toby3d/home/internal/urlutil"
|
|
)
|
|
|
|
type pageUseCase struct {
|
|
pages page.Repository
|
|
statics static.Repository
|
|
}
|
|
|
|
func NewPageUseCase(pages page.Repository, statics static.Repository) page.UseCase {
|
|
return &pageUseCase{
|
|
pages: pages,
|
|
statics: statics,
|
|
}
|
|
}
|
|
|
|
func (ucase *pageUseCase) Do(ctx context.Context, lang language.Tag, p string) (*domain.Page, error) {
|
|
ext := path.Ext(p)
|
|
if ext == ".html" {
|
|
p = p[:len(p)-len(ext)]
|
|
}
|
|
|
|
hasTrailingSlash := p[len(p)-1] == '/'
|
|
head, tail := urlutil.ShiftPath(p)
|
|
targets := []string{path.Join(head, tail)}
|
|
|
|
if tail == "/" {
|
|
if hasTrailingSlash || ext == "" {
|
|
targets = append([]string{path.Join(head, "index")}, targets...)
|
|
}
|
|
|
|
targets = append(targets, head)
|
|
}
|
|
|
|
for i := range targets {
|
|
out, err := ucase.pages.Get(ctx, lang, targets[i])
|
|
if err != nil {
|
|
continue
|
|
}
|
|
|
|
out.Resources, _, _ = ucase.statics.Fetch(ctx, out.File.Dir()+"*")
|
|
|
|
return out, nil
|
|
}
|
|
|
|
return nil, fmt.Errorf("cannot find page on path '%s': %w", p, page.ErrNotExist)
|
|
}
|