summaryrefslogtreecommitdiff
path: root/pkg/helpers/json.go
blob: 664a9846a550e11745f4e1fafa729f139233eddb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package helpers

import (
	"encoding/json"
	"fmt"
	"log/slog"
	"net/http"
)

func Decode(r *http.Request, data any) error {
	if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
		return fmt.Errorf("failed to decode json: %w", err)
	}
	return nil
}

func Encode(w http.ResponseWriter, status int, data any) error {
	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
}