dsfsdfsd34324 2019-08-28 07:13
浏览 46
已采纳

无法在Go Chi路由器中阅读“ request.Body”

Consider the following code in main/entry function

    r := chi.NewRouter()
    r.Use(middleware.RequestID)
    r.Use(middleware.RealIP)
    r.Use(middleware.Logger)
    r.Use(middleware.Recoverer)

    r.Post("/book", controllers.CreateBook)
    http.ListenAndServe(":3333", r)

and CreateBook Function defined as

    func CreateBook(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("content-type", "application/json")
    var bookObj models.Book
    err := json.NewDecoder(r.Body).Decode(&bookObj)
    spew.Dump(bookObj)
    collection := db.Client.Database("bookdb").Collection("book")
    ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
    insertResult, err := collection.InsertOne(ctx, bookObj)
    if err != nil {
        log.Fatal(err)
    }
    json.NewEncoder(w).Encode(insertResult)
  }

Book Model

//exporting attributes here solved the issue type Book struct { ID primitive.ObjectID json:"id,omitempty" bson:"id,omitempty" name string json:"name,omitempty" bson:"name,omitempty" author string json:"author,omitempty" bson:"author,omitempty" isbn string json:"isbn,omitempty" bson:"isbn,omitempty" }

However json.NewDecoder(r.Body).Decode(&bookObj) dont parse any things as req.Body is empty, no error thrown, its about chi's Render function, Can anyone help me to disable Render and Bind functions of Chi, I would like to parse body through JSON decoders only.

Thanks.

  • 写回答

1条回答 默认 最新

  • douda5706 2019-08-28 10:47
    关注

    Exporting all fields of structs resolved the issue. thanks @mkopriva

    type Book struct {
    ID     primitive.ObjectID `json:"id,omitempty" bson:"id,omitempty"`
    Name   string             `json:"name,omitempty" bson:"name,omitempty"`
    Author string             `json:"author,omitempty" bson:"author,omitempty"`
    ISBN   string             `json:"isbn,omitempty" bson:"isbn,omitempty"`
    

    }

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。