duanben1909 2017-06-20 21:40
浏览 52
已采纳

在render.Bind中清空空的http.Request.Body

I am using github.com/pressly/chi to build this simple program where I try to decode some JSON from the http.Request.Body:

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)
}

When I don't use render.Bind() (from "github.com/pressly/chi/render"), it works as expected.

However, when I uncomment the line err := render.Bind(r, &p) and I comment the line err := json.NewDecoder(r.Body).Decode(&p), it panics with EOF :

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

and thus the json.Decode() fails.

Am I doing something wrong or is the http.Request.Body is already read somewhere else before render.Bind() is called?

  • 写回答

1条回答 默认 最新

  • dongzi1959 2017-06-20 22:07
    关注

    render.Bind's purpose is to perform decode and execute Bind(r) to do post decode operations.

    For eg.:

    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
    }
    

    If you have to do only JSON decode no other actions needs to be done after decode with respect to decoded values. Just use:

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

    OR

    // Use wrapper method from chi DecodeJSON
    err := render.DecodeJSON(r.Body, &p)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP