monorepo/cloud/maplepress-backend/pkg/httpresponse/response.go

31 lines
803 B
Go

package httpresponse
import (
"encoding/json"
"net/http"
)
// JSON writes a JSON response with pretty printing (indented)
func JSON(w http.ResponseWriter, code int, data interface{}) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
encoder := json.NewEncoder(w)
encoder.SetIndent("", " ")
return encoder.Encode(data)
}
// OK writes a 200 JSON response with pretty printing
func OK(w http.ResponseWriter, data interface{}) error {
return JSON(w, http.StatusOK, data)
}
// Created writes a 201 JSON response with pretty printing
func Created(w http.ResponseWriter, data interface{}) error {
return JSON(w, http.StatusCreated, data)
}
// NoContent writes a 204 No Content response
func NoContent(w http.ResponseWriter) {
w.WriteHeader(http.StatusNoContent)
}