Files
cv-site/internal/httputil/response.go
T

38 lines
1016 B
Go
Raw Normal View History

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)
}