chore(tfstated): refactor helpers to their own package

This commit is contained in:
Julien Dessaux 2024-11-17 00:05:22 +01:00
parent 5b6da56089
commit 25ed1188ed
Signed by: adyxax
GPG key ID: F92E51B86E07177E
11 changed files with 78 additions and 62 deletions

25
pkg/helpers/json.go Normal file
View file

@ -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
}