Using nested struct to save master-detail POST request

121 views
Skip to first unread message

Hugh Myrie

unread,
Mar 21, 2021, 4:37:18 PM3/21/21
to golang-nuts
I am able to decode the body of a POST request using json.NewDecoder(r.Body)., then save the result to a database. 

Example:

type Product struct {
ID    int  `json:"id"`   
Description  string  `json:"description"`
Price   float64 `json:"price"`
Packsize int `json:"packsize"`
Count1 int `json:"count1"`
Bin string `json:"bin"`
Qoh int `json:"qoh"`
}

items := []Product{}

err := json.NewDecoder(r.Body).Decode(&items)
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
fmt.Println("Error occurs here")
log.Printf(err.Error())
        return
    }

How can I use a nested struct to produce two slices from an incoming (master-detail) POST request, in the form:

[{receipt: 1, date: '01/01/2021', customer: 'Cash' , subtotal: 10.70,
 detail: [{receipt: 1, description: 'item1', price: 2.00, qty: 2},
              {receipt: 1, description: 'item2', price: 2.50, qty: 1},
              {receipt: 1, description: 'item3', price: 4.20, qty: 1}]
]

I am trying to avoid sending two POST requests, master followed by detail.

Shulhan

unread,
Mar 22, 2021, 12:29:49 AM3/22/21
to Hugh Myrie, golang-nuts
You can add new field with type is slice of struct inside the Product,
for example,

Details []ProductDetail `json:"detail"`

Reply all
Reply to author
Forward
0 new messages