mirror of
https://github.com/Kugelschieber/migo.git
synced 2026-01-18 06:40:29 +00:00
43 lines
766 B
Go
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)
|
|
}
|
|
}
|