[Proposal] Allow passing a custom json marshal/unmarshal implementation
- 主要语言
- Go
- 星标
- 10.8k
- 派生
- 1.3k
- 平均合并
- 2 天 36 分钟
- 30 天内合并 PR
- 26
描述
Currently the json marshalling cannot be easily replaces with a different implementation like https://github.com/goccy/go-json or https://github.com/json-iterator/go. The only way to do so would be to copy the transport implementations and inject the json marshaller there.
I propose an API that accepts a custom implementation supplied directly to the transport at fields:
```go
type Decoder interface {
Decode(v interface{}) error
UseNumber()
}
type Json interface {
Marshal(v interface{}) ([]byte, error)
NewDecoder(r io.Reader) Decoder
}
type POST struct {
// Map of all headers that are added to graphql response. If not
// set, only one header: Content-Type: application/json will be set.
ResponseHeaders map[string][]string
Json Json // Json being an interface so it can be implemented however the user wants
}
```
The library can supply a default implementation based on `encoding/json`:
```go
var DefaultJson Json = jsonImpl{}
type jsonImpl struct{}
func (jsonImpl) Marshal(v interface{}) ([]byte, error) {
return json.Marshal(v)
}
func (jsonImpl) NewDecoder(r io.Reader) Decoder {
return json.NewDecoder(r)
}
```
Since there already exists [a file](https://github.com/99designs/gqlgen/blob/master/graphql/handler/transport/util.go) that handles most json marshalling it can be updated to accept the json implementation and fallback if one is not supplied:
```go
func writeJson(json Json, w io.Writer, response *graphql.Response) {
if json == nil {
json = DefaultJson
}
b, err := json.Marshal(response)
if err != nil {
panic(err)
}
w.Write(b)
}
```
This will add a slight overhead of checking for the implementation but will not break existing codebases.
贡献指南
调研方向
该 issue 提议向 transport 层添加自定义 JSON marshal/unmarshal 接口。首先检查 graphql/handler/transport/util.go 中现有的 JSON 处理方式。了解 POST transport 当前如何使用 encoding/json。目标是修改 transport,使其接受一个 Json 接口,提供默认实现,并更新 writeJson 以使用它。检查是否已有关于 JSON marshalling 的测试,以确保兼容性。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- go
- 领域
- api, backend
- Issue 类型
- 功能
- 难度
- 3/5
- 预计耗时
- 1-2 天
- 活跃度
- 停滞
- 描述清晰度
- 描述清楚
- 新手友好度
- 45/100