show-rss/src/cmd/server/handler/ui.go

67 lines
1.3 KiB
Go

package handler
import (
"encoding/json"
"fmt"
"net/http"
"os"
"path"
"show-rss/src/feeds"
"slices"
"text/template"
)
var dir = func() string {
if v := os.Getenv("UI_D"); v != "" {
return v
}
return "./src/cmd/server/handler/testdata"
}()
func (h Handler) ui(w http.ResponseWriter, r *http.Request) error {
fs := http.FileServer(http.Dir(dir))
if path.Base(r.URL.Path) == "ui" {
return h.uiIndex(w, r)
}
http.StripPrefix("/experimental/ui", fs).ServeHTTP(w, r)
return nil
}
func (h Handler) uiIndex(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
b, _ := os.ReadFile(path.Join(dir, "index.tmpl"))
tmpl := template.New(r.URL.Path).Funcs(template.FuncMap{
"feeds": func() ([]feeds.Feed, error) {
all := []feeds.Feed{}
err := feeds.ForEach(ctx, func(f feeds.Feed) error {
all = append(all, f)
return ctx.Err()
})
return all, err
},
"feedsVersionFields": func() []string {
b, _ := json.Marshal(feeds.Version{})
var m map[string]any
json.Unmarshal(b, &m)
ks := make([]string, 0, len(m))
for k := range m {
ks = append(ks, k)
}
slices.Sort(ks)
return ks
},
"namespan": func(k string, v any) string {
return fmt.Sprintf("<span name=%q>%s</span>", k, v)
},
})
tmpl, err := tmpl.Parse(string(b))
if err != nil {
return err
}
return tmpl.Execute(w, nil)
}