首页 > 解决方案 > 如何使用golang快速获取邮递员的表单数据?

问题描述

我正在使用邮递员检索表单数据,但代码太长。有什么方法可以获取简短的数据吗?这是我正在使用的代码:

Customer结构:

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

我得到 3 个表单值。假设我需要得到 50 个值,那么函数会大得多。

标签: gostruct

解决方案


您可以自己解析 HTTP 请求正文,如下所示

选项1:

import (
    "github.com/gin-gonic/gin"
    "github.com/gin-gonic/gin/json"
    "log"
)
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"`
}

func process(context *gin.Context) {
    var customer = &Customer{}
    req := context.Request
    err := json.NewDecoder(req.Body).Decode(customer)
    if err != nil {
        log.Fatal()
    }
}

选项2:

编码映射到解码结构(不推荐)

import (
    "github.com/gin-gonic/gin"
    "encoding/json"
    "bytes"
    "log"
)


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"`
}

func Process(context  *gin.Context) {

    req := context.Request
    var aMap = map[string]interface{}{}
    for key, values := range req.PostForm {
        aMap[key]=values[0]
    }

    var buf = new(bytes.Buffer)
    err := json.NewEncoder(buf).Encode(aMap)
    if err != nil {
        log.Fatal(err)
    }
    var customer = &Customer{}
    json.NewDecoder(buf).Decode(customer)
    if err != nil {
        log.Fatal(err)
    }
}

推荐阅读