30ed21ff7a
- Update all imports from 'constants' to 'c' for brevity - Replace all 'constants.' references with 'c.' - Fix remaining hardcoded content-type headers in httputil - Fix remaining hardcoded User-Agent and Accept headers - Rename CSRF receiver from 'c' to 'csrf' to avoid conflict - Add ContentTypePlainSimple constant for Accept header matching - Fix JSONCached to use proper integer formatting
38 lines
1016 B
Go
38 lines
1016 B
Go
package httputil
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
c "github.com/juanatsap/cv-site/internal/constants"
|
|
)
|
|
|
|
// JSON writes a JSON response with the given status code.
|
|
func JSON(w http.ResponseWriter, status int, data interface{}) error {
|
|
w.Header().Set(c.HeaderContentType, c.ContentTypeJSON)
|
|
w.WriteHeader(status)
|
|
return json.NewEncoder(w).Encode(data)
|
|
}
|
|
|
|
// JSONOk writes a 200 OK JSON response.
|
|
func JSONOk(w http.ResponseWriter, data interface{}) error {
|
|
return JSON(w, http.StatusOK, data)
|
|
}
|
|
|
|
// JSONCached writes a JSON response with caching headers.
|
|
func JSONCached(w http.ResponseWriter, data interface{}, maxAge int) error {
|
|
w.Header().Set(c.HeaderCacheControl, fmt.Sprintf("public, max-age=%d", maxAge))
|
|
return JSONOk(w, data)
|
|
}
|
|
|
|
// HTML sets HTML content type header.
|
|
func HTML(w http.ResponseWriter) {
|
|
w.Header().Set(c.HeaderContentType, c.ContentTypeHTML)
|
|
}
|
|
|
|
// NoContent sends a 204 No Content response.
|
|
func NoContent(w http.ResponseWriter) {
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|