Initial cloud-services repo - gateway service + pkg modules
This commit is contained in:
41
pkg/utils/querystring/querystring.go
Normal file
41
pkg/utils/querystring/querystring.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package querystring
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func SplitIntArray(value string) ([]int64, error) {
|
||||
items := strings.Split(value, ",")
|
||||
result := make([]int64, len(items))
|
||||
|
||||
for i, item := range items {
|
||||
val, err := strconv.ParseInt(item, 10, 64)
|
||||
if err != nil || val < 1 {
|
||||
return result, fmt.Errorf("invalid id %s", item)
|
||||
}
|
||||
result[i] = val
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func ConvertStringToInt(input string) (int, error) {
|
||||
// Try converting the string to float
|
||||
floatValue, err := strconv.ParseFloat(input, 64)
|
||||
if err == nil {
|
||||
// Float conversion successful, return the integer part
|
||||
return int(floatValue), nil
|
||||
}
|
||||
|
||||
// Float conversion failed, try converting the string to integer
|
||||
intValue, err := strconv.Atoi(input)
|
||||
if err == nil {
|
||||
// Integer conversion successful, return the integer value
|
||||
return intValue, nil
|
||||
}
|
||||
|
||||
// Conversion failed
|
||||
return 0, err
|
||||
}
|
||||
25
pkg/utils/querystring/querystring_test.go
Normal file
25
pkg/utils/querystring/querystring_test.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package querystring_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"fiskerinc.com/modules/utils/querystring"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestConvertStringToInt(t *testing.T) {
|
||||
input := "3.14"
|
||||
result, err := querystring.ConvertStringToInt(input)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, result, 3)
|
||||
|
||||
input = "447"
|
||||
result, err = querystring.ConvertStringToInt(input)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, result, 447)
|
||||
|
||||
input = "abc"
|
||||
result, err = querystring.ConvertStringToInt(input)
|
||||
assert.NotNil(t, err)
|
||||
assert.Equal(t, result, 0)
|
||||
}
|
||||
Reference in New Issue
Block a user