Reputation: 95
I try to query database and use query result to create json like these
[ {"TransID": "Transaction ID1",ProductID": ["ProID1","ProID2","ProID3","ProID4" ]},
{"TransID": "Transaction ID2","ProductID": ["ProID5","ProID6" ]} ]
so I create type struct from
type DataRecent []struct {
TransID string `json:"transID"`
ProductID []string `json:"productID"`}
and golang code is
var dataRecent DataRecent
var recent [5]string
for _, Trans := range recent {
if Trans != "" {
var TransID, ProductID string
selectTrans, err := db.Query("select transaction_id, product_id from detail where transaction_id = ?", Trans)
var arr []string
for selectTrans.Next() {
if err != nil {
panic(err.Error())
}
errTrans := selectTrans.Scan(&TransID, &ProductID)
if errTrans != nil {
panic(errTrans.Error())
}
arr = append(arr, ProductID)
}
}
dataRecent.TransID = Trans
dataRecent.ProductID = arr
}
c.JSON(http.StatusOK, gin.H{"status": "success", "message": "Find transactions success", "recent_trans": dataRecent})
defer db.Close()
but I can't build the code and got error
dataRecent.TransID undefined (type DataRecent has no field or method TransID) dataRecent.ProductID undefined (type DataRecent has no field or method ProductID)
I don't know what to do and stuck with these for a week. I am new programmer for golang. Help me pleae, Thank you
Upvotes: 0
Views: 228
Reputation: 107
looks like dataRecent isn't initialized. I suggest you use dataRecent := DataRecent{}
instead of var dataRecent DataRecent
.
some other insights:
I'm not sure if you've omitted the usage of make
of the recent string array, or you're not aware you need to make()
it. Anyway, arrays are values in Go, and if you're new to Go I strongly suggest you use slices instead. https://blog.golang.org/go-slices-usage-and-internals
Also, I'm not sure why you have to panic()
in case you've found an error (in the words of Dave Cheney, panic
means "game over man" - https://dave.cheney.net/tag/panic)
Upvotes: 0
Reputation: 610
Just remove the array when you create the struct
type DataRecent struct {
TransID string `json:"transID"`
ProductID []string `json:"productID"`
}
and do
var dataRecent []DataRecent
it will works for you.
Upvotes: 2