6

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?

4
  • 1
    The cleanest way is to probably forgo decoding the request body, and just put the values directly into a struct. Commented May 18, 2017 at 15:47
  • Answered, but, I have to ask... how in the world did you end up with a table with 500 columns? Commented May 18, 2017 at 16:12
  • 1
    Check out the binding library, which is designed to solve this problem Commented May 18, 2017 at 16:44
  • @Adrian Hi Adrian, I didn't made that design. Indeed I was surprised when I saw it, but it responds to a standar stablished in the company on which I am working, is strange but it's ok Commented May 18, 2017 at 19:35

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.