PageRenderTime 46ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/stringutils/formatToStructFieldName.go

https://bitbucket.org/B-Core/file-server
Go | 36 lines | 28 code | 6 blank | 2 comment | 12 complexity | f0dd1df5106387e446d0bbca86803e9a MD5 | raw file
  1. package stringutils
  2. import (
  3. "regexp"
  4. "strings"
  5. "unicode"
  6. )
  7. var regID = regexp.MustCompile("^(?i)id$")
  8. var regUUID = regexp.MustCompile("^(?i)uuid$")
  9. var regCSS = regexp.MustCompile("^(?i)css$")
  10. // FormatToStructFieldName format a string
  11. // to have the go struct Field Name convention
  12. func FormatToStructFieldName(in string) string {
  13. runes := []rune(in)
  14. length := len(runes)
  15. var out []rune
  16. for i := 0; i < length; i++ {
  17. if i == 0 && unicode.IsLower(runes[i]) && len(runes) > 1 {
  18. out = append(out, unicode.ToUpper(runes[i]))
  19. } else if i > 0 && unicode.IsUpper(runes[i]) {
  20. out = append(out, unicode.ToLower(runes[i]))
  21. } else {
  22. out = append(out, runes[i])
  23. }
  24. }
  25. sOut := string(out)
  26. if regID.MatchString(sOut) || regUUID.MatchString(sOut) || regCSS.MatchString(sOut) {
  27. sOut = strings.ToUpper(sOut)
  28. }
  29. return sOut
  30. }