From fa4ab932c3ff5ac8c7556e19d9ee1be5e1fbbb81 Mon Sep 17 00:00:00 2001 From: ikbalkazanc Date: Fri, 9 Sep 2022 16:53:11 +0300 Subject: [PATCH] added first case to lowercase naming strategy --- extra/naming_strategy.go | 15 ++++++++++++++- extra/naming_strategy_test.go | 19 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/extra/naming_strategy.go b/extra/naming_strategy.go index 916b57d0..09a21246 100644 --- a/extra/naming_strategy.go +++ b/extra/naming_strategy.go @@ -18,7 +18,7 @@ type namingStrategyExtension struct { func (extension *namingStrategyExtension) UpdateStructDescriptor(structDescriptor *jsoniter.StructDescriptor) { for _, binding := range structDescriptor.Fields { - if unicode.IsLower(rune(binding.Field.Name()[0])) || binding.Field.Name()[0] == '_'{ + if unicode.IsLower(rune(binding.Field.Name()[0])) || binding.Field.Name()[0] == '_' { continue } tag, hastag := binding.Field.Tag().Lookup("json") @@ -53,3 +53,16 @@ func LowerCaseWithUnderscores(name string) string { } return string(newName) } + +// FirstCaseToLower one strategy to SetNamingStrategy for. It will change HelloWorld to helloWorld. +func FirstCaseToLower(name string) string { + newName := []rune{} + for i, c := range name { + if i == 0 { + newName = append(newName, unicode.ToLower(c)) + } else { + newName = append(newName, c) + } + } + return string(newName) +} diff --git a/extra/naming_strategy_test.go b/extra/naming_strategy_test.go index 9d418b37..fff7cbea 100644 --- a/extra/naming_strategy_test.go +++ b/extra/naming_strategy_test.go @@ -64,3 +64,22 @@ func Test_set_naming_strategy_with_private_field(t *testing.T) { should.Nil(err) should.Equal(`{"user_name":"allen"}`, string(output)) } + +func Test_first_case_to_lower(t *testing.T) { + should := require.New(t) + should.Equal("helloWorld", FirstCaseToLower("HelloWorld")) + should.Equal("hello_World", FirstCaseToLower("Hello_World")) +} + +func Test_first_case_to_lower_with_first_case_already_lowercase(t *testing.T) { + should := require.New(t) + should.Equal("helloWorld", FirstCaseToLower("helloWorld")) +} + +func Test_first_case_to_lower_with_first_case_be_anything(t *testing.T) { + should := require.New(t) + should.Equal("_HelloWorld", FirstCaseToLower("_HelloWorld")) + should.Equal("*HelloWorld", FirstCaseToLower("*HelloWorld")) + should.Equal("?HelloWorld", FirstCaseToLower("?HelloWorld")) + should.Equal(".HelloWorld", FirstCaseToLower(".HelloWorld")) +}