github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/jsoni/extra/naming_strategy.go (about)

     1  package extra
     2  
     3  import (
     4  	"strings"
     5  	"unicode"
     6  
     7  	"github.com/bingoohuang/gg/pkg/jsoni"
     8  )
     9  
    10  // SetNamingStrategy rename struct fields uniformly
    11  func SetNamingStrategy(translate func(string) string) {
    12  	jsoni.RegisterExtension(&NamingStrategyExtension{Translate: translate})
    13  }
    14  
    15  type NamingStrategyExtension struct {
    16  	jsoni.DummyExtension
    17  	Translate func(string) string
    18  }
    19  
    20  func (e *NamingStrategyExtension) UpdateStructDescriptor(sd *jsoni.StructDescriptor) {
    21  	for _, f := range sd.Fields {
    22  		if unicode.IsLower(rune(f.Field.Name()[0])) || f.Field.Name()[0] == '_' {
    23  			continue
    24  		}
    25  		if tag, ok := f.Field.Tag().Lookup("json"); ok {
    26  			tagParts := strings.Split(tag, ",")
    27  			if tagParts[0] == "-" {
    28  				continue // hidden field
    29  			}
    30  			if tagParts[0] != "" {
    31  				continue // field explicitly named
    32  			}
    33  		}
    34  		f.ToNames = []string{e.Translate(f.Field.Name())}
    35  		f.FromNames = []string{e.Translate(f.Field.Name())}
    36  	}
    37  }
    38  
    39  // LowerCaseWithUnderscores one strategy to SetNamingStrategy for. It will change HelloWorld to hello_world.
    40  func LowerCaseWithUnderscores(name string) string {
    41  	var newName []rune
    42  	for i, c := range name {
    43  		if i == 0 {
    44  			newName = append(newName, unicode.ToLower(c))
    45  		} else {
    46  			if unicode.IsUpper(c) {
    47  				newName = append(newName, '_')
    48  				newName = append(newName, unicode.ToLower(c))
    49  			} else {
    50  				newName = append(newName, c)
    51  			}
    52  		}
    53  	}
    54  	return string(newName)
    55  }