From d6a9219234e340ba4455e45b1105be18782c5c78 Mon Sep 17 00:00:00 2001 From: Mathieu Corbin Date: Fri, 1 Jul 2022 18:01:38 +0200 Subject: [PATCH] Configure the schema format if the email validator is set This commit set the schema format to "email" if the email validator is set on a field. --- openapi/generator.go | 4 ++++ openapi/generator_test.go | 17 +++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/openapi/generator.go b/openapi/generator.go index 5b0c1cf..73c1b53 100644 --- a/openapi/generator.go +++ b/openapi/generator.go @@ -1177,6 +1177,10 @@ func (g *Generator) updateSchemaValidation(schema *Schema, sf reflect.StructFiel if t == "dive" || t == "keys" { break } + if t == "email" { + schema.Format = "email" + break + } // Tags can be joined together with an OR operator. parts := strings.Split(t, "|") diff --git a/openapi/generator_test.go b/openapi/generator_test.go index 6cf08a0..8a9b68b 100644 --- a/openapi/generator_test.go +++ b/openapi/generator_test.go @@ -361,6 +361,23 @@ func TestNewSchemaFromStructFieldErrors(t *testing.T) { assert.Equal(t, reflect.Bool, fe.Type.Kind()) } +func TestNewSchemaFromStructFieldFormat(t *testing.T) { + g := gen(t) + + type T struct { + A string `validate:"email" default:"foobar"` + } + typ := reflect.TypeOf(T{}) + + // Field A is required and has a default value. + sor := g.newSchemaFromStructField(typ.Field(0), true, "A", typ) + assert.NotNil(t, sor) + assert.Len(t, g.Errors(), 1) + assert.Implements(t, (*error)(nil), g.Errors()[0]) + assert.NotEmpty(t, g.Errors()[0].Error()) + assert.Equal(t, sor.Schema.Format, "email") +} + func diffJSON(a, b []byte) (bool, error) { var j, j2 interface{} if err := json.Unmarshal(a, &j); err != nil {