My listing may receive a filter parameter, but this parameter is mandatory.
status := r.FormValue("status")
var bet []*Bet
if err := db.C(collectionName).Find(bson.M{"status": status}).Sort("-data-criacao").All(&bet); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
If the parameter was not informed, the query returns no result.
To return all the results, I used to do the following
var bet []*Bet
if err := db.C(collectionName).Find(nil).Sort("-data-criacao").All(&bet); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
How can I meet both alternatives?
Simply use an if
statement to construct your query based on whether the parameter is supplied.
Something like this:
status := r.FormValue("status")
var bet []*Bet
var filter bson.M
if status != "" {
filter = bson.M{"status": status}
}
err := db.C(collectionName).Find(filter).Sort("-data-criacao").All(&bet)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}