2024-11-17 00:05:22 +01:00
|
|
|
package helpers
|
2024-10-01 17:32:14 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"log/slog"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
2024-11-17 00:05:22 +01:00
|
|
|
func Decode(r *http.Request, data any) error {
|
2024-10-01 17:32:14 +02:00
|
|
|
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
|
|
|
|
return fmt.Errorf("failed to decode json: %w", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-11-17 00:05:22 +01:00
|
|
|
func Encode(w http.ResponseWriter, status int, data any) error {
|
2024-10-01 17:32:14 +02:00
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
w.WriteHeader(status)
|
|
|
|
if err := json.NewEncoder(w).Encode(data); err != nil {
|
|
|
|
slog.Error("failed to encode json", "err", err)
|
|
|
|
return fmt.Errorf("failed to encode json: %w", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|