added more general response handler

This commit is contained in:
$(pass /github/name)
2024-07-07 15:49:28 +02:00
parent ea29ec22bf
commit 90edd26ae0
4 changed files with 70 additions and 16 deletions

View File

@@ -0,0 +1,35 @@
package utils
import (
"encoding/json"
"net/http"
)
type ResponseHandler struct {
Writer http.ResponseWriter
}
type Response struct {
Status string `json:"status"`
Message string `json:"message"`
}
func NewResponseHandler(w http.ResponseWriter) *ResponseHandler {
return &ResponseHandler{Writer: w}
}
func (rh *ResponseHandler) RespondWithError(code int, message string) {
response := Response{
Status: "error",
Message: message,
}
rh.Writer.Header().Set("Content-Type", "application/json")
rh.Writer.WriteHeader(code)
json.NewEncoder(rh.Writer).Encode(response)
}
func (rh *ResponseHandler) RespondWithJSON(code int, payload interface{}) {
rh.Writer.Header().Set("Content-Type", "application/json")
rh.Writer.WriteHeader(code)
json.NewEncoder(rh.Writer).Encode(payload)
}