diff options
author | Julien Dessaux | 2024-11-17 00:05:22 +0100 |
---|---|---|
committer | Julien Dessaux | 2024-12-17 23:19:18 +0100 |
commit | 25ed1188ed970a19675befef12afe68045565c4a (patch) | |
tree | 5cfc55047d833400028fb69a7f069f5cedecaacd /pkg/helpers/json.go | |
parent | fix(tfstated): hash passwords instead of relying on the database encryption key (diff) | |
download | tfstated-25ed1188ed970a19675befef12afe68045565c4a.tar.gz tfstated-25ed1188ed970a19675befef12afe68045565c4a.tar.bz2 tfstated-25ed1188ed970a19675befef12afe68045565c4a.zip |
chore(tfstated): refactor helpers to their own package
Diffstat (limited to 'pkg/helpers/json.go')
-rw-r--r-- | pkg/helpers/json.go | 25 |
1 files changed, 25 insertions, 0 deletions
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 +} |