json - 是否有(惯用或任何其他)方法将附加上下文/状态传递给嵌套结构的 UnmarshalJSON([]byte) 接口实现?
问题描述
我的应用程序中有以下结构
// foo.go
type FooList struct {
Fools []*foo `json:"list"`
// maybe
Req *http.Request
}
type Foo struct {
//...
//...
}
func (f *Foo) UnmarshalJSON(data []byte) error {
// need access to request.Context here
// or request scoped state, how?
// is it possible to access FooList.Req?
}
// handler.go
func handleSomething(w http.ResponseWriter, r *http.Request) {
//...
// some additional work happens in goroutines - a few can be started up
go func(r *http.Request) {
fools := &fooList{Req: r} // could have a field here for r, but how can the nested struct access it?
// call a service that returns a foo list and decode
resp, err = httpClient.Do(...)
err = json.NewDecoder(resp.Body).Decode(&fools) // triggers custom unmarshalling, needs "r"
// ...
// ...
}(r)
//...
// ...
}
我希望我正在做的事情不是太神秘,并且是可以理解的。我的 HTTP 请求处理程序依赖于外部服务来处理一些可以反序列化的数据(以 JSON 形式返回)。在此过程中,我想使用自定义解组器来影响生成的实例状态,并且我需要传入的请求上下文(例如)可用于 UnmarshalJSON() 函数。
这可能吗?我错过了一些明显的东西吗?
解决方案
这可能吗?
不。
我错过了一些明显的东西吗?
不。
Go 基本上没有魔法。如果你想完成某件事,你必须像以前那样去做。(我将只使用 Context 而不是整个 Request 并使用未导出的字段。)