Handling an optional boolean query parameter in Go

Viewed 51

I am working on an API where the GET request has a set of filters that can be applied to the data.

One of the filters is binary and non-mandatory.

My curent approach is using *bool instead of bool to differentiate between specified vs non-specified values of the filter.

var isVisible *bool
isVisibleParam := query.Get("is_visible")

isVisibleParsed, err := strconv.ParseBool(isVisibleParam)
if err != nil {
  isVisible = nil
} else {
  isVisible = &isVisibleParsed

And in SQL to cover that case correctly, I have $param is NULL OR is_visible = $param

The code above looks a bit ugly even though it works correctly. Is there a more elegant way to achieve the same?

1 Answers

I think using a bool pointer to differentiate "specified" vs "non-specified" looks good. On the SQL side maybe you could check if it's not null and only then append the condition to the query. As for the code, maybe condensing it makes it nicer:

var isVisible *bool
if isVisibleParam, err := strconv.ParseBool(query.Get("is_visible")); err == nil {
    isVisible = &isVisibleParam
}
Related