package main import ( "embed" "flag" "fmt" "html/template" "io" "log" "net/http" "net/http/httputil" "net/url" "strings" "time" ) var ( port = flag.Int("port", 42069, "port to listen on") https = flag.Bool("https", false, "use https") serverStartTime = time.Now() ) //go:embed templates/404.html.template var notFoundString string var notFoundTemplate = template.Must(template.New("notFound").Parse(notFoundString)) func notFound(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) type args struct { Path string } if err := notFoundTemplate.Execute(w, args{Path: r.URL.Path}); err != nil { log.Printf("Warning: notFound: %s", err) } } //go:embed templates/index.html.template var indexString string var indexTemplate = template.Must(template.New("index").Parse(indexString)) func index(w http.ResponseWriter, _ *http.Request) { if err := indexTemplate.Execute(w, nil); err != nil { log.Printf("Warning: index: %s", err) } } //go:embed static var staticFiles embed.FS func static(w http.ResponseWriter, r *http.Request) { fileName := strings.TrimPrefix(r.URL.Path, "/") f, err := staticFiles.Open(fileName) if err != nil { notFound(w, r) return } defer f.Close() http.ServeContent(w, r, fileName, serverStartTime, f.(io.ReadSeeker)) } func main() { flag.Parse() mux := http.NewServeMux() jellyfinURL, err := url.Parse("http://localhost:8096") if err != nil { log.Fatalf("Jellyfin URL: %s", err) } mux.Handle("/cinema/", httputil.NewSingleHostReverseProxy(jellyfinURL)) mux.HandleFunc("/static/", static) mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/" { index(w, r) } else { notFound(w, r) } }) httpServer := http.Server{ Addr: fmt.Sprintf(":%d", *port), Handler: mux, ReadTimeout: 5 * time.Second, WriteTimeout: 5 * time.Second, } log.Printf("Listening on %q", httpServer.Addr) if *https { log.Fatal(httpServer.ListenAndServeTLS("/var/lib/acme/roseh.moe/cert.pem", "/var/lib/acme/roseh.moe/key.pem")) } else { log.Fatal(httpServer.ListenAndServe()) } }