dongwupei7803 2018-11-18 08:13
浏览 369
已采纳

在Golang中读取请求正文两次(重复)

This question already has an answer here:

type ValidationModel struct {
    Name     string `json:"name" valid:"alpha,required~Name is required"`
    Email    string `json:"email" valid:"email~Enter a valid email.,required~Email is required."`
    Password string `json:"password" valid:"required~Password is required"`
}

validationModel := ValidationModel{}

json.NewDecoder(r.Body).Decode(&validationModel)

_, err := govalidator.ValidateStruct(validationModel)

First I am validating the request body using govalidator.

type UserModel struct {
    ID           bson.ObjectId `json:"_id" bson:"_id"`
    Name         string        `json:"name" bson:"name"`
    Email        string        `json:"email" bson:"email"`
    Password     string        `json:"password,omitempty" bson:"-"`
    PasswordHash string        `json:"-" bson:"passwordHash"`
    Salt         string        `json:"-" bson:"salt"`
    Token        string        `json:"token,omitempty" bson:"-"`
}


user := models.UserModel{}
json.NewDecoder(r.Body).Decode(&user)

fmt.Println(user)

And after validating the request, again I am decoding the request body into user struct, but the request body has been read once using validationModel, so when I try to again decode it into user, it is not giving me any values.

I can think of two solutions here:

  1. Store request body in one separate variable, and use that variable two times.

  2. Copy validationModel values in user.

But I don't have any idea about to implement these approaches and which approach is best to follow. Or is there any other solution which can be implemented?

Thanks in advance.

</div>
  • 写回答

1条回答 默认 最新

  • dspld86684 2018-11-18 08:45
    关注

    Storing the data can be easily done with ioutil.ReadAll():

    data, err := ioutil.ReadAll(r.Body)
    

    If you need the data back as a io.Reader (which is how the r.Body is), then you can use bytes.NewReader():

    reader := bytes.NewReader(data)
    

    And ACTUALLY, r.Body is a io.ReadCloser, so if you need that you can use ioutil.NopCloser() in conjunction with bytes.NewReader():

    reader := ioutil.NopCloser(bytes.NewReader(data))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题