繁体   English   中英

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

[英]Chi empty http.Request.Body in render.Bind

我正在使用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恐慌:

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

因此json.Decode()失败。

我是在http.Request.Body什么还是在http.Request.Body render.Bind()之前已经在其他地方读取了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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM