英文:
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
。然后,你可以使用反射自己将其转换为结构体,或者你可以使用像mapstructure或gorilla/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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论