Skip to content

Commit

Permalink
Fix RequestParam not returning default value if the number param is n…
Browse files Browse the repository at this point in the history
…ot a number (#9)
  • Loading branch information
andrysds authored Nov 15, 2019
1 parent 6f7b69c commit 23d7e28
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 5 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Clarity
[![Build Status](https://travis-ci.org/andrysds/clarity.svg)](https://travis-ci.org/andrysds/clarity) [![codecov](https://codecov.io/gh/andrysds/clarity/branch/master/graph/badge.svg)](https://codecov.io/gh/andrysds/clarity) [![Go Report Card](https://goreportcard.com/badge/github.com/andrysds/clarity)](https://goreportcard.com/report/github.com/andrysds/clarity) [![GoDoc](https://godoc.org/github.com/andrysds/clarity?status.svg)](https://godoc.org/github.com/andrysds/clarity)

Random but useful and essential utilites for your Go projects.
Few utility functions for Go

## Installing

Expand Down
14 changes: 10 additions & 4 deletions http_request.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,17 @@ func RequestParam(URL *url.URL, key string, defaultValue interface{}) interface{
case string:
return value
case int:
intValue, _ := strconv.Atoi(value)
return intValue
if intValue, err := strconv.Atoi(value); err != nil {
return defaultValue
} else {
return intValue
}
case int64:
int64Value, _ := strconv.ParseInt(value, 10, 64)
return int64Value
if int64Value, err := strconv.ParseInt(value, 10, 64); err != nil {
return int64Value
} else {
return int64Value
}
case []string:
return strings.Split(value, ",")
}
Expand Down
9 changes: 9 additions & 0 deletions http_request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
func TestRequestParamTest(t *testing.T) {
var result interface{}
URL, _ := url.Parse("http://localhost?key=value&number=1&long_number=10&array[]=elem1,elem2")
wrongURL, _ := url.Parse("http://localhost?key=value&number=one&long_number=ten&array[]=elem1,elem2")
defaults := map[string]interface{}{
"s": "default",
"i": 0,
Expand Down Expand Up @@ -46,10 +47,18 @@ func TestRequestParamTest(t *testing.T) {
result = RequestParam(URL, "number", defaults["i"]).(int)
assert.Equal(t, result, 1)

// wrong int param
result = RequestParam(wrongURL, "number", defaults["i"]).(int)
assert.Equal(t, result, 0)

// int64 param
result = RequestParam(URL, "long_number", defaults["i64"]).(int64)
assert.Equal(t, result, int64(10))

// wrong int64 param
result = RequestParam(wrongURL, "long_number", defaults["i64"]).(int64)
assert.Equal(t, result, int64(0))

// array param
result = RequestParam(URL, "array", defaults["a"]).([]string)
assert.Equal(t, result, []string{"elem1", "elem2"})
Expand Down

0 comments on commit 23d7e28

Please sign in to comment.