Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SetGenericSystemLoopbackIPs() needs a "don't care" option #235

Open
chrismarget-j opened this issue Mar 8, 2024 · 0 comments
Open

SetGenericSystemLoopbackIPs() needs a "don't care" option #235

chrismarget-j opened this issue Mar 8, 2024 · 0 comments

Comments

@chrismarget-j
Copy link
Collaborator

Similar to #230.

When marshaling JSON for /api/blueprints/%s/systems/%s/loopback/%d, we need to distinguish between these two cases:

  • I don't care about one of the addresses
  • I intende to clear one of the addresses

This seems to be close:

type foo struct {
	Name string
	IP   *net.IP
}

func (o foo) MarshalJSON() ([]byte, error) {
	type raw struct {
		Name string  `json:"name"`
		IP   *string `json:"ip_address"`
	}

	r := raw{Name: o.Name}

	if o.IP != nil {
		if len(*o.IP) == 0 {
			// non-nil net.IP with empty length == clear the value from the API
			r.IP = toPtr("") // send an empty string
		} else {
			// nil net.IP == don't care
			r.IP = toPtr(o.IP.String()) // send null
		}
	}

	return json.Marshal(&r)
}

func TestFoo(t *testing.T) {
	type testCase struct {
		v foo
		e string
	}

	testCases := map[string]testCase{
		"nil": {
			v: foo{Name: "nil", IP: nil},
			e: `{"name":"nil","ip_address":null}`,
		},
		"empty": {
			v: foo{Name: "empty", IP: &net.IP{}},
			e: `{"name":"empty","ip_address":""}`,
		},
		"with_value": {
			v: foo{Name: "with_value", IP: &net.IP{10, 0, 0, 5}},
			e: `{"name":"with_value","ip_address":"10.0.0.5"}`,
		},
	}

	for tName, tCase := range testCases {
		tName, tCase := tName, tCase
		t.Run(tName, func(t *testing.T) {
			t.Parallel()
			b, err := json.Marshal(&tCase.v)
			require.NoError(t, err)

			t.Log(tName, string(b))
		})
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant