From be03834d4506655662b7edf0124101bc9f58e184 Mon Sep 17 00:00:00 2001 From: Matthias Schneider Date: Tue, 8 Mar 2022 13:49:19 +0100 Subject: [PATCH] feat: Example/SchemaExample: allow \r \n \t --- operation.go | 12 +++++++++++- operation_test.go | 9 ++++++--- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/operation.go b/operation.go index 5d35963cc..0e2df5abb 100644 --- a/operation.go +++ b/operation.go @@ -535,6 +535,9 @@ func setDefault(param *spec.Parameter, schemaType string, value string) error { return nil } +// controlCharReplacer replaces \r \n \t in example string values +var controlCharReplacer = strings.NewReplacer(`\r`, "\r", `\n`, "\n", `\t`, "\t") + func setSchemaExample(param *spec.Parameter, schemaType string, value string) error { val, err := defineType(schemaType, value) if err != nil { @@ -544,7 +547,14 @@ func setSchemaExample(param *spec.Parameter, schemaType string, value string) er if param.Schema == nil { return nil } - param.Schema.Example = val + + switch v := val.(type) { + case string: + param.Schema.Example = controlCharReplacer.Replace(v) + default: + param.Schema.Example = val + } + return nil } diff --git a/operation_test.go b/operation_test.go index 1f2f03e08..1e01b6b77 100644 --- a/operation_test.go +++ b/operation_test.go @@ -1918,13 +1918,16 @@ func TestParseParamCommentBySchemaExampleUnsupportedType(t *testing.T) { param.Schema = &spec.Schema{} setSchemaExample(¶m, STRING, "string value") - assert.Equal(t, param.Schema.Example, "string value") + assert.Equal(t, "string value", param.Schema.Example) setSchemaExample(¶m, INTEGER, "10") - assert.Equal(t, param.Schema.Example, 10) + assert.Equal(t, 10, param.Schema.Example) setSchemaExample(¶m, NUMBER, "10") - assert.Equal(t, param.Schema.Example, float64(10)) + assert.Equal(t, float64(10), param.Schema.Example) + + setSchemaExample(¶m, STRING, "string \\r\\nvalue") + assert.Equal(t, "string \r\nvalue", param.Schema.Example) } func TestParseParamArrayWithEnums(t *testing.T) {