Skip to content

Commit

Permalink
Change 'targetPort' from int to string (#2274)
Browse files Browse the repository at this point in the history
targetPort can reference a port or well known service name
  • Loading branch information
wbreza committed May 19, 2023
1 parent fbffad1 commit a5acb8c
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 2 deletions.
33 changes: 31 additions & 2 deletions cli/azd/pkg/tools/kubectl/models.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
package kubectl

import (
"encoding/json"
"fmt"
)

type ResourceType string

const (
Expand Down Expand Up @@ -106,11 +111,35 @@ type ServiceStatus struct {
}

type Port struct {
Port int `json:"port"`
TargetPort int `json:"targetPort"`
Port int `json:"port"`
// The target port can be a valid port number or well known service name like 'redis'
TargetPort any `json:"targetPort"`
Protocol string `json:"protocol"`
}

func (p *Port) UnmarshalJSON(data []byte) error {
var aux struct {
Port int `json:"port"`
TargetPort any `json:"targetPort"`
Protocol string `json:"protocol"`
}

if err := json.Unmarshal(data, &aux); err != nil {
return err
}

p.Port = aux.Port
p.Protocol = aux.Protocol

switch v := aux.TargetPort.(type) {
case string, int, float64:
p.TargetPort = v
return nil
default:
return fmt.Errorf("unsupported type for TargetPort")
}
}

type KubeConfig struct {
ApiVersion string `yaml:"apiVersion"`
Clusters []*KubeCluster `yaml:"clusters"`
Expand Down
46 changes: 46 additions & 0 deletions cli/azd/pkg/tools/kubectl/models_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package kubectl

import (
"encoding/json"
"fmt"
"testing"

"github.com/stretchr/testify/require"
)

func Test_Port_TargetPort_Unmarshalling(t *testing.T) {
tests := map[string]struct {
input string
expected string
expectError bool
}{
"StringValue": {
input: "{ \"port\": 80, \"protocol\": \"http\", \"targetPort\": \"redis\" }",
expected: "redis",
},
"IntValue": {
input: "{ \"port\": 80, \"protocol\": \"http\", \"targetPort\": 6379 }",
expected: "6379",
},
"InvalidType": {
input: "{ \"port\": 80, \"protocol\": \"http\", \"targetPort\": { \"foo\": \"bar\" } }",
expectError: true,
},
}

for name, test := range tests {
t.Run(name, func(t *testing.T) {
var port Port
err := json.Unmarshal([]byte(test.input), &port)
if test.expectError {
require.Error(t, err)
return
}

require.NoError(t, err)
require.Equal(t, test.expected, fmt.Sprint(port.TargetPort))
require.Equal(t, 80, port.Port)
require.Equal(t, "http", port.Protocol)
})
}
}

0 comments on commit a5acb8c

Please sign in to comment.