是否有惯用或其他方式将其他上下文/状态传递给嵌套结构的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返回)。在此过程中,我想使用一个自定义的unmarshaller来影响结果实例状态,并且我需要传入的请求上下文(例如)对UnmarshalJSON()函数可用。

这可能吗?我缺少明显的东西吗?

解决方法

这可能吗?

否。

我缺少明显的东西吗?

否。

Go基本上没有魔术。如果您想完成某件事,则必须像以前一样去做。 (我将只使用上下文而不是整个Request,并使用未导出的字段。)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...