8000 v2: MarshalINI and UnmarshalINI for custom key values by unknwon · Pull Request #427 · go-ini/ini · GitHub
[go: up one dir, main page]

Skip to content

v2: MarshalINI and UnmarshalINI for custom key values - #427

Open
unknwon wants to merge 1 commit into
v2-nextfrom
v2-marshal-ini
Open

unknwon wants to merge 1 commit into
v2-nextfrom
v2-marshal-ini

Conversation

@unknwon
@unknwon unknwon commented Nov 10, 2026 •
Copy link
Copy Markdown
Member

Stacked on the v2 PR (go-ini/ini PR 425), so this merges into v2-next.

Types can now format and parse their own key values, as requested in go-ini/ini issue 353:

type Marshaler interface {
	MarshalINI() ([]byte, error)
}

type Unmarshaler interface {
	UnmarshalINI([]byte) error
}

Where they apply

  • Reading: MapTo, StrictMapTo and Unmarshal call UnmarshalINI with the value as Key.String returns it. This covers a plain field, a pointer field, and each element of a slice field. List, ValidList, StrictList, In and Range call it too, so ini.List[Permission](k, ",") works.
  • Writing: ReflectFrom and Marshal call MarshalINI for the same kinds of field, with either a value or a pointer receiver.
  • Errors: an error from UnmarshalINI leaves the field unchanged in MapTo, as for any value that doesn't parse, and StrictMapTo and StrictList return it. An error from MarshalINI is returned by Marshal and ReflectFrom.

Rules

  1. A type that implements either interface uses it whatever its kind. A named int enum reads Perm = write instead of failing on a non-number.
  2. A struct type that implements either interface maps to a key, not to a section, so a type such as a host:port pair can be one value. A struct without them still maps to a section, as before.
  3. time.Time keeps its own handling.

Tests

  • TestMarshalerUnmarshaler covers an enum and a struct type: reading, writing and reading back, errors in MapTo, StrictMapTo and Marshal, and the generic accessors. All four subtests fail without the change.
  • FuzzStructMapping now has enum fields of every shape. A 55-second run found nothing.

A type with MarshalINI or UnmarshalINI formats or parses its own key
value in ReflectFrom, Marshal, MapTo, StrictMapTo and Unmarshal, as a
field, a pointer field or a slice element. List, ValidList, StrictList,
In and Range use UnmarshalINI too. An error leaves the field unchanged,
and StrictMapTo, StrictList and Marshal return it.

A struct type that implements either interface maps to a key instead of
a section, so types such as a host:port pair can be one value.

This branch has not been deployed

No deployments
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

Successfully merging this pull request may close these issues.

1 participant

0