converge/cmd/converge/fileserver.go
Erik Brakkee b1f7304eeb Now rendering the index.html using the Templ library.
This is in preparation for:
1. creating a base page
2. using tabs: Home, Using, Downloads, Status
3. htmx
2024-07-28 21:31:17 +02:00

60 lines
1.3 KiB
Go

package main
import (
"converge/pkg/templates"
"net/http"
"os"
"path/filepath"
"strings"
)
type FileHandlerFilter struct {
dir string
fileHandler http.Handler
}
func NewFileHandler(dir string) *FileHandlerFilter {
handler := FileHandlerFilter{
dir: dir,
fileHandler: http.FileServer(http.Dir(dir)),
}
return &handler
}
func (handler FileHandlerFilter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
contextPath := r.URL.Path
path := filepath.Join(handler.dir, contextPath)
fileInfo, err := os.Stat(path)
if err == nil && fileInfo.IsDir() {
contextPath = filepath.Join(contextPath, "index.html")
}
if !strings.HasSuffix(contextPath, ".html") {
handler.fileHandler.ServeHTTP(w, r)
return
}
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
secure := ""
if r.TLS == nil {
secure = ""
} else {
secure = "s"
}
for _, header := range []string{"X-Forwarded-Proto", "X-Scheme", "X-Forwarded-Scheme"} {
values := r.Header.Values(header)
for _, value := range values {
if strings.ToLower(value) == "https" {
secure = "s"
}
}
}
username, _ := os.LookupEnv("CONVERGE_USERNAME")
templates.Index(secure, r.Host, username).Render(
r.Context(), w)
}