From 206182fcb9c4ab2b49e8e44c6a2711a988e3f968 Mon Sep 17 00:00:00 2001 From: Julien Dessaux Date: Sun, 17 Nov 2024 00:05:22 +0100 Subject: chore(tfstated): refactored helpers to their own package --- pkg/helpers/json.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 pkg/helpers/json.go (limited to 'pkg/helpers/json.go') diff --git a/pkg/helpers/json.go b/pkg/helpers/json.go new file mode 100644 index 0000000..664a984 --- /dev/null +++ b/pkg/helpers/json.go @@ -0,0 +1,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 +} -- cgit v1.2.3