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.