package web import ( "embed" "html/template" "io/fs" "log" "net/http" "sync" "time" ) //go:embed templates/*.html static/* var assets embed.FS type page struct { Title string Newer *newerView } type server struct { fetcher NewerFetcher now func() time.Time logger *log.Logger zone *time.Location tmpl *template.Template cacheMu sync.Mutex cache map[string]cacheEntry } func NewHandler(fetcher NewerFetcher, now func() time.Time, logger *log.Logger) http.Handler { tmpl := template.Must(template.ParseFS(assets, "templates/*.html")) staticFiles, err := fs.Sub(assets, "static") if err != nil { panic(err) } zone, err := time.LoadLocation("Asia/Tokyo") if err != nil { panic(err) } s := &server{fetcher: fetcher, now: now, logger: logger, zone: zone, tmpl: tmpl, cache: make(map[string]cacheEntry)} mux := http.NewServeMux() mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServerFS(staticFiles))) mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") _, _ = w.Write([]byte("ok\n")) }) mux.HandleFunc("GET /{$}", s.home) mux.HandleFunc("GET /newer", s.newerFragment) for path, title := range map[string]string{ "GET /queue": "待ち行列", "GET /subscriptions": "登録番組", "GET /library": "ライブラリ", } { mux.HandleFunc(path, func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") if err := s.tmpl.ExecuteTemplate(w, "layout", page{Title: title}); err != nil { http.Error(w, "template error", http.StatusInternalServerError) } }) } return mux }