dtf579777 2018-04-26 11:31
浏览 91
已采纳

如何使用golang通过邮递员以短方式获取表单数据?

I am retrieving form data using postman, but the code is too long. Is there is any method for getting the data in short form? Here's the code I am using:

Customer struct:

type Customer struct {
 FirstName        string `json:"first_name" bson:"first_name"`
 LastName         string `json:"last_name" bson:"last_name"`
 Email            string `json:"email" bson:"email"`
}  
type Customers []Customer

type new_user struct {
 first_name     string 
 last_name      string 
 email          string
}

Function for retrieving the form data called by the route:

function GetData(c *gin.Context){
 first_name := c.PostForm("first_name")
 last_name := c.PostForm("last_name")
 email := c.PostForm("email")
 reqBody := new(new_user)
 err := c.Bind(reqBody)
 if err != nil {
    fmt.Println(err)
 }
 customer.FirstName = first_name
 customer.LastName = last_name
 customer.Email = email
}

I'm getting 3 form values. Suppose I need to get 50 values, then the function will be much bigger.

  • 写回答

2条回答 默认 最新

  • dsjq6977 2018-04-27 03:03
    关注

    As the mkopriva tells me a short way to do this. I got the answer for it. It can be shorter by doing the following code.

    type Customer struct {
     FirstName string `form:"first_name" json:"first_name" bson:"first_name"`
     LastName  string `form:"last_name" json:"last_name" bson:"last_name"`
     Email     string `form:"email" json:"email" bson:"email"`
    }
    

    In the function the code is:-

    customer := new(Customer)
    if err := c.Bind(customer); err != nil {
        return nil, err
    }
    fmt.Println(customer)
    

    It will print the data from the form-data of the postman.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?