go - 如何使用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 个值,那么函数会大得多。
解决方案
您可以自己解析 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)
}
}
推荐阅读
- html - 如何更改我的 css 以使其在 Safari 和 Chrome 上呈现相同的效果?
- swift - 值替换后恢复字符串插值
- sqlalchemy - sqlalchemy 连接查询的问题 - 从孩子那里获取下一个日期
- react-native - Expo for Web 编译失败,因为原生基础模块
- javascript - 在 php 中完成进程后更改 JS/jQuery 中的按钮文本
- excel - 添加参数以从动态 URL 连接和抓取数据
- java - 为什么 Axon Framework 中的 RetryScheduler 在 NoHandlerForCommandException 后不重试?
- azure-cosmosdb - Azure Cosmos DB - WHERE 条件下的 SQL API 范围筛选器
- python - 如何获得访问令牌
- javascript - 如何重定向角度组件