From a98f43d087f3605856b935de68296e4486812f15 Mon Sep 17 00:00:00 2001 From: ispiroglu Date: Wed, 25 Sep 2024 16:25:03 +0300 Subject: [PATCH] feat: add uint and float support into swagger --- modules/swagger/defs_test.go | 31 +++++++++++++++++++++++++++++++ modules/swagger/json.go | 9 ++++++++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/modules/swagger/defs_test.go b/modules/swagger/defs_test.go index 76639dc..cf4ca0a 100644 --- a/modules/swagger/defs_test.go +++ b/modules/swagger/defs_test.go @@ -15,6 +15,8 @@ type testStruct struct { Field5 *string `json:"field5"` Field6 map[string]int `json:"field6" validate:"required"` Field7 string `json:"-"` + Field8 uint32 `json:"field8"` + Field9 float64 `json:"field9"` } type anotherStruct struct { @@ -119,6 +121,35 @@ func TestBuildModelDefinition(t *testing.T) { if _, ok := props.(m)["field7"]; ok { t.Errorf("field7 is not expected in defs as it tagged with '-'") } + + if p, ok := props.(m)["field8"]; !ok { + t.Errorf("Expected field8 in properties, not found") + } else { + if field, ok := p.(m); ok { + if field["type"] != "integer" { + t.Errorf("Expected field8 to be of type int") + } + + if field["format"] != "uint32" { + t.Errorf("Expected field8 to be of format uint32") + } + } + } + + if p, ok := props.(m)["field9"]; !ok { + t.Errorf("Expected field9 in properties, not found") + } else { + if field, ok := p.(m); ok { + if field["type"] != "number" { + t.Errorf("Expected field9 to be of type number") + } + + if field["format"] != "float64" { + t.Errorf("Expected field9 to be of format float64") + } + } + } + } else { t.Errorf("Expected properties to be a map, got %T", defs["testStruct"].(m)["properties"]) } diff --git a/modules/swagger/json.go b/modules/swagger/json.go index 742cde6..8d9cf83 100644 --- a/modules/swagger/json.go +++ b/modules/swagger/json.go @@ -74,13 +74,20 @@ func withDefinitionPrefix(s string) string { } func getPrimitiveType(t reflect.Type) m { - if kp := t.Kind().String(); strings.HasPrefix(kp, "int") { + if kp := t.Kind().String(); strings.HasPrefix(kp, "int") || strings.HasPrefix(kp, "uint") { return m{ "type": "integer", "format": kp, } } + if kp := t.Kind().String(); strings.HasPrefix(kp, "float") { + return m{ + "type": "number", + "format": kp, + } + } + k := t.Kind().String() if t.Kind() == reflect.Bool {