Supports dynamic filtering of struct fields #314
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
What
In encoding, you can dynamically filter the fields in the structure by creating a
json.FieldQuery
, adding it tocontext.Context
usingjson.SetFieldQueryToContext
and then passing it tojson.MarshalContext
.This is a type-safe operation, so it is faster than filtering using
map[string]interface{}
.Motivation
When providing the REST API or GraphQL API, you may want to select and encode the fields of a structure.
In such a case, the conventional method requires to prepare a value of type
map[string]interface{}
, transfer the value of the selected field to map once, and then encode it.This process is not only costly to create a map, but also a slow operation because you can't benefit from static typing.
So in go-json, if you creates
json.FieldQuery
that has information about selected fields and set it incontext.Context
and pass it to encoder,it will dynamically filter according to the contents of json.FieldQuery.
By supporting this by the encoder itself, it can be operated at high speed.
You can also apply the filter when writing arbitrary processing in MarshalJSON by combining it with
MarshalJSON(context.Context)([]byte, error)
.See examples
Example1
Example2
Benchmark