Files
migo/api/util.go
2023-08-01 23:19:14 +02:00

43 lines
766 B
Go

package api
import (
"encoding/json"
"io"
"log"
"net/http"
"syscall"
)
type apiError struct {
Validation map[string]string `json:"validation"`
Err []error `json:"error"`
}
func decodeJSON(w http.ResponseWriter, r *http.Request, req any) error {
body, err := io.ReadAll(r.Body)
if err != nil {
return err
}
if err := json.Unmarshal(body, &req); err != nil {
return err
}
return nil
}
func encodeJSON(w http.ResponseWriter, resp any) {
respBody, err := json.Marshal(resp)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Printf("Error marshalling response: %v", err)
return
}
if _, err := w.Write(respBody); err != nil && err != syscall.EPIPE {
log.Printf("Error sending response: %v", err)
}
}