问题描述
我的应用程序具有以下结构
// 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返回)。在此过程中,我想使用一个自定义的unmarshaller来影响结果实例状态,并且我需要传入的请求上下文(例如)对UnmarshalJSON()函数可用。
这可能吗?我缺少明显的东西吗?
解决方法
这可能吗?
否。
我缺少明显的东西吗?
否。
Go基本上没有魔术。如果您想完成某件事,则必须像以前一样去做。 (我将只使用上下文而不是整个Request,并使用未导出的字段。)