json - 在 render.Bind 中置空 http.Request.Body

标签 json http go go-chi

我正在使用 github.com/pressly/chi构建这个简单的程序,我尝试从 http.Request.Body 中解码一些 JSON:

package main

import (
    "encoding/json"
    "fmt"
    "net/http"

    "github.com/pressly/chi"
    "github.com/pressly/chi/render"
)

type Test struct {
    Name string `json:"name"`
}

func (p *Test) Bind(r *http.Request) error {
    err := json.NewDecoder(r.Body).Decode(p)
    if err != nil {
        return err
    }
    return nil
}

func main() {
    r := chi.NewRouter()

    r.Post("/products", func(w http.ResponseWriter, r *http.Request) {
        var p Test
        // err := render.Bind(r, &p)
        err := json.NewDecoder(r.Body).Decode(&p)

        if err != nil {
            panic(err)
        }

        fmt.Println(p)
    })

    http.ListenAndServe(":8080", r)
}

当我不使用 render.Bind()(来自 "github.com/pressly/chi/render")时,它会按预期工作。

但是,当我取消注释行 err := render.Bind(r, &p) 并且我注释行 err := json.NewDecoder(r.Body).Decode( &p),它因 EOF 出现 panic :

2017/06/20 22:26:39 http: panic serving 127.0.0.1:39696: EOF

因此 json.Decode() 失败。

是我做错了什么,还是 http.Request.Body 在调用 render.Bind() 之前已经在其他地方读取了?

最佳答案

render.Bind目的是执行解码,执行Bind(r)做解码后操作。

例如:

type Test struct {
   Name string `json:"name"`
}

func (p *Test) Bind(r *http.Request) error {
   // At this point, Decode is already done by `chi`
   p.Name = p.Name + " after decode"
  return nil
}

如果您只需要进行 JSON 解码,则解码后无需对解码值执行其他操作。只需使用:

// Use Directly JSON decoder of std pkg
err := json.NewDecoder(r.Body).Decode(&p)

// Use wrapper method from chi DecodeJSON
err := render.DecodeJSON(r.Body, &p)

关于json - 在 render.Bind 中置空 http.Request.Body,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44663496/

相关文章:

json - 如何通过 Node 请求从另一个域获取json文件?

jquery - 获取同一行中的所有 <td>

http - 在服务到服务通信方面,http2 是否比 http1.1 有性能优势?

go - 如何在浏览器中发送带有grpc请求的数组?

go - 如何从golang中的base64编码文件中提取文件扩展名?

windows - 尝试构建docker镜像时,出现 ""gcc“: executable file not found in $PATH"

javascript - Web2py - 无法连接 'str' 和 'NoneType' 对象

python - 使用 Python 创建 D3 嵌套 JSON 数据

web-services - Elixir - Simple Plug 示例在每次请求时两次调用调用方法

c# - 如何访问 ApiController 中的 Response