funcs.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. package ktgen
  2. import (
  3. "fmt"
  4. "log"
  5. "strings"
  6. "text/template"
  7. "git.i2edu.net/i2/go-zero/tools/goctl/api/util"
  8. "github.com/iancoleman/strcase"
  9. )
  10. var funcsMap = template.FuncMap{
  11. "lowCamelCase": lowCamelCase,
  12. "routeToFuncName": routeToFuncName,
  13. "parseType": parseType,
  14. "add": add,
  15. "upperCase": upperCase,
  16. }
  17. func lowCamelCase(s string) string {
  18. if len(s) < 1 {
  19. return ""
  20. }
  21. s = util.ToCamelCase(util.ToSnakeCase(s))
  22. return util.ToLower(s[:1]) + s[1:]
  23. }
  24. func routeToFuncName(method, path string) string {
  25. if !strings.HasPrefix(path, "/") {
  26. path = "/" + path
  27. }
  28. path = strings.ReplaceAll(path, "/", "_")
  29. path = strings.ReplaceAll(path, "-", "_")
  30. path = strings.ReplaceAll(path, ":", "With_")
  31. return strings.ToLower(method) + strcase.ToCamel(path)
  32. }
  33. func parseType(t string) string {
  34. t = strings.Replace(t, "*", "", -1)
  35. if strings.HasPrefix(t, "[]") {
  36. return "List<" + parseType(t[2:]) + ">"
  37. }
  38. if strings.HasPrefix(t, "map") {
  39. tys, e := decomposeType(t)
  40. if e != nil {
  41. log.Fatal(e)
  42. }
  43. if len(tys) != 2 {
  44. log.Fatal("Map type number !=2")
  45. }
  46. return "Map<String," + parseType(tys[1]) + ">"
  47. }
  48. switch t {
  49. case "string":
  50. return "String"
  51. case "int", "int32", "int64":
  52. return "Int"
  53. case "float", "float32", "float64":
  54. return "Double"
  55. case "bool":
  56. return "Boolean"
  57. default:
  58. return t
  59. }
  60. }
  61. func decomposeType(t string) (result []string, err error) {
  62. add := func(tp string) error {
  63. ret, err := decomposeType(tp)
  64. if err != nil {
  65. return err
  66. }
  67. result = append(result, ret...)
  68. return nil
  69. }
  70. if strings.HasPrefix(t, "map") {
  71. t = strings.ReplaceAll(t, "map", "")
  72. if t[0] == '[' {
  73. pos := strings.Index(t, "]")
  74. if pos > 1 {
  75. if err = add(t[1:pos]); err != nil {
  76. return
  77. }
  78. if len(t) > pos+1 {
  79. err = add(t[pos+1:])
  80. return
  81. }
  82. }
  83. }
  84. } else if strings.HasPrefix(t, "[]") {
  85. if len(t) > 2 {
  86. err = add(t[2:])
  87. return
  88. }
  89. } else if strings.HasPrefix(t, "*") {
  90. err = add(t[1:])
  91. return
  92. } else {
  93. result = append(result, t)
  94. return
  95. }
  96. err = fmt.Errorf("bad type %q", t)
  97. return
  98. }
  99. func add(a, i int) int {
  100. return a + i
  101. }
  102. func upperCase(s string) string {
  103. return strings.ToUpper(s)
  104. }