package handlers import ( "encoding/json" "html/template" "log" "net/http" ) // noCacheHeaders sets headers to prevent browser caching func noCacheHeaders(w http.ResponseWriter) { w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") w.Header().Set("Pragma", "no-cache") w.Header().Set("Expires", "0") } // JSONResponse writes data as JSON with appropriate headers func JSONResponse(w http.ResponseWriter, data interface{}) { w.Header().Set("Content-Type", "application/json") noCacheHeaders(w) _ = json.NewEncoder(w).Encode(data) } // JSONError writes an error response as JSON func JSONError(w http.ResponseWriter, status int, msg string, err error) { if err != nil { log.Printf("Error: %s: %v", msg, err) } http.Error(w, msg, status) } // HTMLResponse renders an HTML template func HTMLResponse(w http.ResponseWriter, tmpl *template.Template, name string, data interface{}) { w.Header().Set("Content-Type", "text/html; charset=utf-8") noCacheHeaders(w) if err := tmpl.ExecuteTemplate(w, name, data); err != nil { http.Error(w, "Failed to render template", http.StatusInternalServerError) log.Printf("Error rendering template %s: %v", name, err) } } // HTMLString writes an HTML string directly func HTMLString(w http.ResponseWriter, html string) { w.Header().Set("Content-Type", "text/html") _, _ = w.Write([]byte(html)) }