From 472960588cde5b865374f1c13abaafca9c8189a0 Mon Sep 17 00:00:00 2001 From: JT Olds Date: Wed, 24 May 2017 16:47:21 -0600 Subject: [PATCH] new numerical parsers --- whparse/query.go | 78 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/whparse/query.go b/whparse/query.go index b6566da..453a1d3 100644 --- a/whparse/query.go +++ b/whparse/query.go @@ -34,6 +34,45 @@ func OptInt64(val string, def int64) int64 { return rv } +// OptUint64 parses val and returns the integer value in question, unless +// parsing fails, in which case the default def is returned. +func OptUint64(val string, def uint64) uint64 { + if val == "" { + return def + } + rv, err := strconv.ParseUint(val, 10, 64) + if err != nil { + return def + } + return rv +} + +// OptInt32 parses val and returns the integer value in question, unless +// parsing fails, in which case the default def is returned. +func OptInt32(val string, def int32) int32 { + if val == "" { + return def + } + rv, err := strconv.ParseInt(val, 10, 32) + if err != nil { + return def + } + return int32(rv) +} + +// OptUint32 parses val and returns the integer value in question, unless +// parsing fails, in which case the default def is returned. +func OptUint32(val string, def uint32) uint32 { + if val == "" { + return def + } + rv, err := strconv.ParseUint(val, 10, 32) + if err != nil { + return def + } + return uint32(rv) +} + // OptInt parses val and returns the integer value in question, unless // parsing fails, in which case the default def is returned. func OptInt(val string, def int) int { @@ -47,6 +86,19 @@ func OptInt(val string, def int) int { return int(rv) } +// OptUint parses val and returns the integer value in question, unless +// parsing fails, in which case the default def is returned. +func OptUint(val string, def uint) uint { + if val == "" { + return def + } + rv, err := strconv.ParseUint(val, 10, 0) + if err != nil { + return def + } + return uint(rv) +} + // OptBool parses val and returns the bool value in question, unless // parsing fails, in which case the default def is returned. func OptBool(val string, def bool) bool { @@ -59,3 +111,29 @@ func OptBool(val string, def bool) bool { } return rv } + +// OptFloat64 parses val and returns the float value in question, unless +// parsing fails, in which case the default def is returned. +func OptFloat64(val string, def float64) float64 { + if val == "" { + return def + } + rv, err := strconv.ParseFloat(val, 64) + if err != nil { + return def + } + return rv +} + +// OptFloat32 parses val and returns the float value in question, unless +// parsing fails, in which case the default def is returned. +func OptFloat32(val string, def float32) float32 { + if val == "" { + return def + } + rv, err := strconv.ParseFloat(val, 32) + if err != nil { + return def + } + return float32(rv) +}