I fetch data from Postgresql and populate a list. If the list is empty I want to redirect to another page. Here is my attempt (that not works):
list := Get(query)
switch list {
case nil:
returns []
fmt.Println("no result")
default:
returns [map[post_id:1 post_subject:Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...] map[post_id:2 post_subject:Vestibulum ante ipsum primis in faucibus orci luctus et ultrices]]
fmt.Println("show result")
}
If Get(query) returns the empty interface, and doesn’t return nil when there are no results, I’m not sure of the right way to do this. I would investigate refactoring that Get function to return a better type, but in the meantime, you could try:
import "reflect"
func isEmpty(v interface{}) bool {
if v == nil {
return true
}
switch v := v.(type) {
case []interface{}: // maybe test for some other types before falling back to reflection
return len(v) == 0
default:
rv := reflect.ValueOf(v)
switch rv.Kind() {
case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String:
return rv.Len() == 0
}
return false
}
}
list := Get(query)
switch {
case isEmpty(list):
// ...
default:
// else
}
@Sibert That checks if there are any key-value pairs in the map, but what I presume is a printed representation of list in your first post:
looks like a slice of maps, so checking the length of the individual map(s) won’t tell you if there are any maps.
I’ve tried to make reasonable guesses about what you’re trying to do based on the pseudo-code and panic messages but your latest example is significantly different than the assumptions I had at the beginning. If you’re trying to check the lengths of the actual maps, your latest Go Playground example will work, but if you’re still looking for something else, can you put that full example into a Go playground and/or some publicly accessible source control repository?
“I fetch data from Postgresql and populate a list. If the list is empty I want to redirect to another page.” In order to tell the user there is no data fetched.
There is TWO options I can think of:
Query the database and check for empty result during the query.
Check if the result of the query when returned.
In some other languages you can do both in a simple way, but Go makes it harder to achieve. For example both #1 and #2 could be done like If list.$linecount=0…
As Go is a different beast and I am a complete newbie, I have hard to understand why checking if the result of a query is empty or not could be simpler.
Something like ErrNoRows is returned by Scan when db.QueryRow but not a list generated by db.Query(…) for some reason.