gpt4 book ai didi

json - 是否有(惯用或任何其他)方法将附加上下文/状态传递给嵌套结构的 UnmarshalJSON([]byte) 接口(interface)实现?

转载 作者:行者123 更新时间:2023-12-01 20:25:47 26 4
gpt4 key购买 nike

我的应用程序中有以下结构

 // 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() 函数。
这可能吗?我错过了一些明显的东西吗?

最佳答案

Is this possible?


不。

Am I missing something obvious?


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

关于json - 是否有(惯用或任何其他)方法将附加上下文/状态传递给嵌套结构的 UnmarshalJSON([]byte) 接口(interface)实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63808130/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com