Support context for MarshalJSON and UnmarshalJSON #248
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.
context.Context
support forMarshaler
andUnmarshaler
json.MarshalContext(context.Context, interface{}, ...json.EncodeOption) ([]byte, error)
json.NewEncoder(io.Writer).EncodeContext(context.Context, interface{}, ...json.EncodeOption) error
json.UnmarshalContext(context.Context, []byte, interface{}, ...json.DecodeOption) error
json.NewDecoder(io.Reader).DecodeContext(context.Context, interface{}) error
Then, if we implemented the following interface, callback it.
Why
I thought there were situations in
MarshalJSON
andUnmashalJSON
where I wanted to usecontext.Context
.For example, we consider the situation that in MarshalJSON, you want to access external middleware, get the data, and then encode it. At this time,
context.Context
may be required when accessing middleware, we want to use thecontext.Context
not created insideMarshalJSON
but used by the caller ofjson.Marshal()
.I show this situation's sample code the following:
In this case, there is no way to pass context.Context to MarshalJSON , so I think that an approach like json.MarshalContext is necessary.