diff --git a/README.md b/README.md index 06724e379..450d3397b 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ Swag converts Go annotations to Swagger Documentation 2.0. We've created a varie - [Add a headers in response](#add-a-headers-in-response) - [Use multiple path params](#use-multiple-path-params) - [Example value of struct](#example-value-of-struct) + - [SchemaExample of body](#schemaexample-of-body) - [Description of struct](#description-of-struct) - [Use swaggertype tag to supported custom type](#use-swaggertype-tag-to-supported-custom-type) - [Use global overrides to support a custom type](#use-global-overrides-to-support-a-custom-type) @@ -613,6 +614,12 @@ type Account struct { } ``` +### SchemaExample of body + +```go +// @Param email body string true "message/rfc822" SchemaExample(Subject: Testmail\r\n\r\nBody Message\r\n) +``` + ### Description of struct ```go 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) {