Skip to content

Fallback to JSON Struct Tags #88

Closed
@steve-gray

Description

@steve-gray

One small bugbear I've had for a long time with MGO is that unlike Mapstructure you can't set the TagName to use on structures. The general use-case here is letting structures be decorated with json annotations, and then having both mapstructure, mgo and pretty much anything else all work off the same tags - so I don't have:

type SomeStruct struct {
   SnakedField int `json:"snaked_field" mapstructure:"snaked_field" bson:"snaked_field"`
}

I've put an option in a fork of the code that enables this by adding a new global flag to the BSON parser, which can be set per-application. This allows for opting-in to using the JSON annotation if, and only if both the new option is enabled and there are no BSON annotations on the structure.

steve-gray@6f2a776

To 'truly' fix this at a BSON encoder level requires a major contract change, because it relies heavily on stateless global functions - so the notion of an encoder/decoder context would need to be added - and it'd break too much compatibility - unless I've missed something.

If folks are happy with it coming in, I can tweak it and submit the PR (or happy for someone to cherry-pick it) - it seems harmless enough and will aid mightily with struct-pollution in codebases. My main use case for MGO is as a provider that's one-of-many/pluggable - and not requiring every user to add 50 struct tags to a model to support all possible storage engines.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions