From 22fce71b7c8ecd1a0313d17bcc3b979ead90bc8e Mon Sep 17 00:00:00 2001 From: Brandur Date: Thu, 24 Aug 2017 10:46:08 -0700 Subject: [PATCH] Support coercion on the "number" type Supports coercion on the JSON schema "number" type like we do already for booleans and integers. --- param/coercer/coercer.go | 9 +++++++++ param/coercer/coercer_test.go | 12 ++++++++++++ 2 files changed, 21 insertions(+) diff --git a/param/coercer/coercer.go b/param/coercer/coercer.go index 4c9a00f3..4f2034a2 100644 --- a/param/coercer/coercer.go +++ b/param/coercer/coercer.go @@ -42,6 +42,13 @@ func CoerceParams(schema *spec.JSONSchema, data map[string]interface{}) { valInt = 0 } data[key] = valInt + + case hasType(subSchema, numberType): + valFloat, err := strconv.ParseFloat(valStr, 64) + if err != nil { + valFloat = 0.0 + } + data[key] = valFloat } } } @@ -57,6 +64,8 @@ const booleanType = "boolean" // integerType is the name of the integer type in a JSON schema. const integerType = "integer" +const numberType = "number" + func hasType(schema *spec.JSONSchema, targetTypeStr string) bool { for _, typeStr := range schema.Type { if typeStr == targetTypeStr { diff --git a/param/coercer/coercer_test.go b/param/coercer/coercer_test.go index 50562a97..a3073aca 100644 --- a/param/coercer/coercer_test.go +++ b/param/coercer/coercer_test.go @@ -31,6 +31,18 @@ func TestCoerceParams_IntegerCoercion(t *testing.T) { assert.Equal(t, 123, data["intkey"]) } +func TestCoerceParams_NumberCoercion(t *testing.T) { + schema := &spec.JSONSchema{Properties: map[string]*spec.JSONSchema{ + "numberkey": {Type: []string{numberType}}, + }} + data := map[string]interface{}{ + "numberkey": "123.45", + } + + CoerceParams(schema, data) + assert.Equal(t, 123.45, data["numberkey"]) +} + func TestCoerceParams_Recursion(t *testing.T) { schema := &spec.JSONSchema{Properties: map[string]*spec.JSONSchema{ "mapkey": {Properties: map[string]*spec.JSONSchema{