In the function Demo1_CallFindAll()
I am trying to return an object from a database.
In foo()
I cannot see it after using Print. However, I call the Demo1_CallFindAll
function and can see an array of objects in it.
Please explain why and correct my code.
func foo(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
var tags = Demo1_CallFindAll()
fmt.Println(tags) // Here I see nothing
js, err := json.Marshal(tags)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
json.NewEncoder(w).Encode("OKOK")
}
func Demo1_CallFindAll()(products []entities.Product) {
db,err:=config.GetMySQLDB()
if err !=nil{
fmt.Println(err)
}else{
productModel := models.ProductModel{
Db:db,
}
products,err := productModel.FindAll()
if err !=nil{
fmt.Println(err)
}else{
fmt.Println(products)//[{1 Nokia1 10 2 true} {2 Nokia2 11 22 false}]
fmt.Println("Product List")
}
}
return
}
The bug is in this line: products,err := productModel.FindAll()
. You used named return parameters in the Demo1_CallFindAll()
functions. Named returned parameters are initialized to their zero value(ref: https://golang.org/doc/effective_go.html#named-results).
But in the line products,err := productModel.FindAll()
, you created a new variable (by :=
) products
and set results in it, not in the return parameter products
. That's why you can not see anything in the foo()
functions. To solve it, change :=
to =
, products,err = productModel.FindAll()
.