summaryrefslogtreecommitdiff
path: root/internal/handlers/response.go
blob: 9a7ab45da9b937e64a60716a7186147c2bfce031 (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
package handlers

import (
	"encoding/json"
	"html/template"
	"log"
	"net/http"
)

// JSONResponse writes data as JSON with appropriate headers
func JSONResponse(w http.ResponseWriter, data interface{}) {
	w.Header().Set("Content-Type", "application/json")
	_ = 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{}) {
	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))
}