Golang Tutorial Extra Step 3 – Golang Nested JSON into Structs

Let’s talk about Nested Structs in Golang. I was trying to pass in parameters in the right way to Go when I have parameters from two different structs to pass in from my frontend. So, how do we do this?
How do I structure things?

We are building Dancingnomads (a dance app for dancers to find partners and events - give it 5 stars on iOS App Store and Google Play Store please! 😉). 

We’re building our Events feature, and we have one struct for Event details (i.e. Event - i.e. events table) and another struct for Event Dances (i.e. EventDance - i.e. event_dances table) that are associated with each other.

How do I Create / Update My Events?

I actually initialize EventDance and update the Events within Event Dance because an Events object is nested within Event Dance.

Note: I use GORM for an ORM

So, eventUpdateAttempt actually calls axios to make the API call. The parameter is the JSON hash. Here’s what you need to know:

– The hash is the exact same structure as are event_dance struct.

– We use the “event” key because the EventDance struct above has an object of Event looking for the json key “event”.

– Inside the event key is our event information that has the same keys as our Event Struct.

– “id”: event_id lets me know whether this is a create / update function to my API for creating or updating an event.

So, that’s what we’re submitting to the backend and how we are receiving the parameters from the frontend. By using the JSON keys and nesting the structure on the frontend to match that of the backend, the backend will know how to DECODE your structure when it needs to decode your JSON request body and put the parameters in the proper fields in your Event Dance and Event structs.

Hope you had fun and learned something today!

Accompanying medium article: https://medium.com/@donaldlee50/golang-tutorial-extra-step-3-ba23b015bdef

Don’t forget to like, comment, and subscribe!!!

========================================================
Reference Links
========================================================
GORM: https://gorm.io/
Axios: https://www.npmjs.com/package/axios
========================================================
Connect with me!
========================================================
Linkedin: https://www.linkedin.com/in/donaldlee50
Instagram: https://www.instagram.com/donlee50/
Twitter: https://twitter.com/donaldlee50
Youtube: https://youtube.com/coursehack
Mailing List: http://bit.ly/coursehack-mailing-list
Coursehack’s Facebook Group: bit.ly/join-coursehack-facebook-group

Don’t forget to like, comment, and subscribe!

Post Author: hatefull