Use text/template for JS files to avoid html/template escaping

This commit is contained in:
Ian Gulliver
2026-02-14 21:51:49 -08:00
parent 9c0b78e78e
commit f31a22d5f8

29
main.go
View File

@@ -10,6 +10,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"html/template" "html/template"
texttemplate "text/template"
"log" "log"
"net/http" "net/http"
"os" "os"
@@ -23,7 +24,10 @@ import (
//go:embed schema.sql //go:embed schema.sql
var schema string var schema string
var templates *template.Template var (
htmlTemplates *template.Template
jsTemplates *texttemplate.Template
)
func main() { func main() {
for _, key := range []string{"PGCONN", "CLIENT_ID", "CLIENT_SECRET"} { for _, key := range []string{"PGCONN", "CLIENT_ID", "CLIENT_SECRET"} {
@@ -47,8 +51,8 @@ func main() {
log.Fatalf("failed to apply schema: %v", err) log.Fatalf("failed to apply schema: %v", err)
} }
templates = template.Must(template.New("").ParseGlob("static/*.html")) htmlTemplates = template.Must(template.New("").ParseGlob("static/*.html"))
template.Must(templates.ParseGlob("static/*.js")) jsTemplates = texttemplate.Must(texttemplate.New("").ParseGlob("static/*.js"))
http.HandleFunc("/", handleStatic) http.HandleFunc("/", handleStatic)
http.HandleFunc("POST /auth/google/callback", handleGoogleCallback) http.HandleFunc("POST /auth/google/callback", handleGoogleCallback)
@@ -90,17 +94,24 @@ func handleStatic(w http.ResponseWriter, r *http.Request) {
name := strings.TrimPrefix(path, "/") name := strings.TrimPrefix(path, "/")
if strings.HasSuffix(name, ".html") || strings.HasSuffix(name, ".js") { if strings.HasSuffix(name, ".html") {
t := templates.Lookup(name) t := htmlTemplates.Lookup(name)
if t == nil { if t == nil {
http.NotFound(w, r) http.NotFound(w, r)
return return
} }
if strings.HasSuffix(name, ".html") { w.Header().Set("Content-Type", "text/html")
w.Header().Set("Content-Type", "text/html") t.Execute(w, templateData())
} else { return
w.Header().Set("Content-Type", "application/javascript") }
if strings.HasSuffix(name, ".js") {
t := jsTemplates.Lookup(name)
if t == nil {
http.NotFound(w, r)
return
} }
w.Header().Set("Content-Type", "application/javascript")
t.Execute(w, templateData()) t.Execute(w, templateData())
return return
} }