dongwupei7803 2018-11-18 08:13
浏览 369


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


_, 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{}


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.

  • 写回答

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 商城生产日期批次库存问题
  • ¥15 esp8266控制共阳极wrgb灯板无法关闭所有led灯
  • ¥100 python读取速度问题
  • ¥15 stm32f407使用DMA问题
  • ¥15 您好 这个API接口该怎么弄 网站搭建好了 API也有 现在就不知道该怎么填写API 不知道怎么用
  • ¥88 用uniapp写一个多端的程序,用到高德地图,用高德的JSAPI吗?
  • ¥20 关于#c++#的问题:水果店管理系统
  • ¥30 dbLinq最新版linq sqlite
  • ¥20 对D盘进行分盘之前没有将visual studio2022卸载掉,现在该如何下载回来
  • ¥15 完成虚拟机环境配置,还有安装kettle