go-netbox icon indicating copy to clipboard operation
go-netbox copied to clipboard

Setting optional attributes to their "empty" value

Open fbreckle opened this issue 5 years ago • 0 comments
trafficstars

Hi,

this is a generalization of tickets like #105 and #106 because it applies to way more attributes than mentioned in these issues.

The problem Setting an optional attribute to its "empty" value (false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string) will remove the attribute from the resulting JSON that is sent to netbox. This means that these values can not be set to their empty values via go-netbox.

The cause This happens because in the swagger.json for optional attributes looks like this (e.g. WritableVirtualMachineWithConfigContext):

"platform": {
          "title": "Platform",
          "type": "integer",
          "x-nullable": true
        },

which translates to

	// Platform
	Platform *int64 `json:"platform,omitempty"`

which in turn will cause Go's json marshaller to omit empty values, which is intended behavior.

This is explained further in https://goswagger.io/faq/faq_model.html#non-required-or-nullable-property

A solution One possible solution which I employ in a personal fork of go-netbox is to add

        "platform": {
          "title": "Platform",
          "type": "integer",
          "x-nullable": true,
          "x-omitempty": false
        },

which will remove the omitempty annotation from the Go struct.

The problem with this solution is that it requires post-procession of the netbox-generated swaggerfile for all optional attributes. I do not know the stance of this repo's maintainers about post-processing the swagger.json file. It definitely feels less "pure" when compared to just fetching the swagger.json from netbox and regenerating the client. On the other hand, a client that cannot update certain attributes to their empty value is really not valuable.

Ideally, this would be fixed upstream by making netbox return a correct swagger file, but their swagger support is on a best-effort basis only.

fbreckle avatar Oct 26 '20 18:10 fbreckle