From 23d7e283e862f89c395489e607135f02391b7ac7 Mon Sep 17 00:00:00 2001 From: andrys daniel Date: Fri, 15 Nov 2019 15:12:54 +0700 Subject: [PATCH] Fix RequestParam not returning default value if the number param is not a number (#9) --- README.md | 2 +- http_request.go | 14 ++++++++++---- http_request_test.go | 9 +++++++++ 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 45ae3db..01872b1 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/http_request.go b/http_request.go index ca89fbc..7061438 100644 --- a/http_request.go +++ b/http_request.go @@ -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, ",") } diff --git a/http_request_test.go b/http_request_test.go index 3b880bc..e897a28 100644 --- a/http_request_test.go +++ b/http_request_test.go @@ -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, @@ -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"})