📖 2 min read (~ 300 words).

Nullable pointers

Swagger 2.0 has no native nullable flag; the go-openapi toolchain uses the x-nullable vendor extension. Options.SetXNullableForPointers decides whether pointer-typed struct fields acquire it automatically. The model below has two pointer fields:

// Profile has required and optional (pointer) fields.
//
// swagger:model
type Profile struct {
	// Name is always present.
	Name string `json:"name"`

	// Nickname is optional.
	Nickname *string `json:"nickname"`

	// Age is optional.
	Age *int32 `json:"age"`
}

Full source: docs/examples/shaping/nullable/nullable.go

Scanned with the option off (default) and on, the pointer fields differ:

Default
{
  "type": "object",
  "title": "Profile has required and optional (pointer) fields.",
  "properties": {
    "age": {
      "description": "Age is optional.",
      "type": "integer",
      "format": "int32",
      "x-go-name": "Age"
    },
    "name": {
      "description": "Name is always present.",
      "type": "string",
      "x-go-name": "Name"
    },
    "nickname": {
      "description": "Nickname is optional.",
      "type": "string",
      "x-go-name": "Nickname"
    }
  },
  "x-go-package": "github.com/go-openapi/codescan/docs/examples/shaping/nullable"
}

Full source: docs/examples/shaping/nullable/testdata/off.json

SetXNullableForPointers: true
{
  "type": "object",
  "title": "Profile has required and optional (pointer) fields.",
  "properties": {
    "age": {
      "description": "Age is optional.",
      "type": "integer",
      "format": "int32",
      "x-go-name": "Age",
      "x-nullable": true
    },
    "name": {
      "description": "Name is always present.",
      "type": "string",
      "x-go-name": "Name"
    },
    "nickname": {
      "description": "Nickname is optional.",
      "type": "string",
      "x-go-name": "Nickname",
      "x-nullable": true
    }
  },
  "x-go-package": "github.com/go-openapi/codescan/docs/examples/shaping/nullable"
}

Full source: docs/examples/shaping/nullable/testdata/on.json

codescan.Run(&codescan.Options{
    Packages:                []string{"./..."},
    ScanModels:              true,
    SetXNullableForPointers: true,
})
Info

omitempty changes the meaning. A pointer field tagged json:"…,omitempty" is treated as optional (may be absent) rather than nullable (may be null), so it does not receive x-nullable even with the option on. Drop omitempty when you mean the value can be present-but-null.