summaryrefslogtreecommitdiff
path: root/internal/handlers/response.go
blob: 34d449163d98ce3eca3733c2344c71b7c42d2c3a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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))
}