2

I have an integer query param "page", that defaults to 1. I can get it from Echo context like this:

var page int
pageString := c.QueryParam("page")
if pageString == "" {
    page = 1
} else {
    var err error
    page, err = strconv.Atoi(pageString)

    if err != nil {
        page = 1
    }
}

While this works, I would kind of prefer to do something like page := c.QueryParamInt("page", 1) but I couldn't find any equivalent in Echo docs. Should I just write my own utility function or is there a better way?

Fluffy
  • 27,504
  • 41
  • 151
  • 234
  • 1
    You could do something like this: https://play.golang.com/p/fu66E8wMtfX but other than that, you'll have to write your own utility functions. – mkopriva Jan 16 '20 at 11:00

2 Answers2

3

You can try something like:

qp := c.QueryParam("page")
page, err := strconv.Atoi(qp)
if err != nil {
        page=1
}

You don't have to write that much ifelse. Hope this helps.

Prakash Kumar
  • 2,554
  • 2
  • 18
  • 28
1

If you plan on parsing many integer params then the best thing would be to write your own utility function:

func QueryParamInt(c echo.Context, name string, default int) int {
  param := c.QueryParam(name)
  result, err := strconv.Atoi(param)
  if err != nil {
    return default
  }
  return result
}

Then use it as you would like.
Other options would be to extend the echo context, more on that here.

Maciej B. Nowak
  • 1,180
  • 7
  • 19