Skip to content

Commit

Permalink
no need for a custom decoder
Browse files Browse the repository at this point in the history
  • Loading branch information
christeredvartsen committed Feb 16, 2024
1 parent 5ddfc87 commit fbb4e19
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 12 deletions.
14 changes: 6 additions & 8 deletions internal/gcp/clusters.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
package gcp

import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"strings"

"github.com/sethvargo/go-envconfig"
)

type (
Expand All @@ -17,19 +15,19 @@ type (
}
)

var _ envconfig.Decoder = (*Clusters)(nil)
var _ json.Unmarshaler = (*Clusters)(nil)

func (c *Clusters) EnvDecode(value string) error {
*c = make(Clusters)
if value == "" {
func (c *Clusters) UnmarshalJSON(value []byte) error {
if len(value) == 0 {
return nil
}
clustersWithStringID := make(map[string]struct {
TeamsFolderID string `json:"teams_folder_id"`
ProjectID string `json:"project_id"`
})

err := json.NewDecoder(strings.NewReader(value)).Decode(&clustersWithStringID)
*c = make(Clusters)
err := json.NewDecoder(bytes.NewReader(value)).Decode(&clustersWithStringID)
if err != nil {
return fmt.Errorf("parse GCP cluster info: %w", err)
}
Expand Down
8 changes: 4 additions & 4 deletions internal/gcp/clusters_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ func TestDecodeJSONToClusters(t *testing.T) {
clusters := make(gcp.Clusters)

t.Run("empty string", func(t *testing.T) {
err := clusters.EnvDecode("")
err := clusters.UnmarshalJSON([]byte(""))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
Expand All @@ -21,7 +21,7 @@ func TestDecodeJSONToClusters(t *testing.T) {
})

t.Run("empty JSON object", func(t *testing.T) {
err := clusters.EnvDecode("{}")
err := clusters.UnmarshalJSON([]byte("{}"))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
Expand All @@ -32,10 +32,10 @@ func TestDecodeJSONToClusters(t *testing.T) {
})

t.Run("JSON with clusters", func(t *testing.T) {
err := clusters.EnvDecode(`{
err := clusters.UnmarshalJSON([]byte(`{
"env1": {"teams_folder_id": "123", "project_id": "some-id-123"},
"env2": {"teams_folder_id": "456", "project_id": "some-id-456"}
}`)
}`))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
Expand Down

0 comments on commit fbb4e19

Please sign in to comment.