将表单值分配给Golang中的结构体。

huangapple go评论89阅读模式
英文:

assign form values to struct in Golang

问题

我正在使用Golang编写一个API-Rest。我正在使用Gorm,所以我有代表数据库表的结构体。在Create中,我接收一个包含值的表单,但现在我对如何立即将所有值分配给结构体有些疑问,因为我有一个包含500个字段的表,我不能逐个进行赋值,我之前是这样做的:

json.NewDecoder(req.Body).Decode(&myobject)

但是那里我必须接收一个Json,而客户端正在向我发送一个表单。那么,有什么清晰和可读的方法可以将这些值分配给结构体吗?

英文:

I am working on a API-Rest in Golang. I'm using Gorm so I have the structs that represent the database tables. In Create I receive a Form with the values, but right now am having a doubt of how can I assign inmediatly all the values to the structure, because I have a table with 5 hundred fields and I cannot make assignments one by one, I was doint in this way:

json.NewDecoder(req.Body).Decode(&myobject)

But there I had to receive a Json, and the client side is sending me a Form. So, how can I assign that values in a clean and readable way?

答案1

得分: 10

没有内置的方法可以将multipart/form-data主体解组为结构体。然而,Go会自动将表单数据解析为map[string][]string,存储在Request.Form中,你可以通过简单的循环将其转换为map[string]string。然后,你可以使用反射自己将其转换为结构体,或者你可以使用像mapstructuregorilla/schema这样的库。

英文:

There is no built-in way of unmarshalling a multipart/form-data body into a struct. However, Go does automatically parse form data into a map[string][]string in Request.Form, which you could convert to a map[string]string with a simple loop. Then you could transfer that to a struct yourself using reflection, or you could use a library like mapstructure or gorilla/schema.

huangapple
  • 本文由 发表于 2017年5月18日 23:44:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/44052311.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定