go-zero/tools/goctl/api/ktgen/funcs.go

78 lines
1.4 KiB
Go
Raw Normal View History

2020-08-14 09:02:32 +08:00
package ktgen
import (
"log"
"strings"
"text/template"
2020-08-14 10:35:35 +08:00
"github.com/iancoleman/strcase"
2020-08-14 10:35:35 +08:00
"github.com/tal-tech/go-zero/tools/goctl/api/util"
2020-08-14 09:02:32 +08:00
)
2020-08-14 10:35:35 +08:00
var funcsMap = template.FuncMap{
"lowCamelCase": lowCamelCase,
"routeToFuncName": routeToFuncName,
"parseType": parseType,
"add": add,
"upperCase": upperCase,
2020-08-14 09:02:32 +08:00
}
2020-08-14 10:35:35 +08:00
2020-08-14 09:02:32 +08:00
func lowCamelCase(s string) string {
if len(s) < 1 {
return ""
}
s = util.ToCamelCase(util.ToSnakeCase(s))
return util.ToLower(s[:1]) + s[1:]
}
func routeToFuncName(method, path string) string {
2020-08-14 09:02:32 +08:00
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
2020-08-14 10:35:35 +08:00
path = strings.ReplaceAll(path, "/", "_")
path = strings.ReplaceAll(path, "-", "_")
path = strings.ReplaceAll(path, ":", "With_")
2020-08-14 09:02:32 +08:00
2020-08-19 16:00:55 +08:00
return strings.ToLower(method) + strcase.ToCamel(path)
2020-08-14 09:02:32 +08:00
}
2020-08-14 10:35:35 +08:00
2020-08-14 09:02:32 +08:00
func parseType(t string) string {
2020-08-14 10:35:35 +08:00
t = strings.Replace(t, "*", "", -1)
if strings.HasPrefix(t, "[]") {
return "List<" + parseType(t[2:]) + ">"
2020-08-14 09:02:32 +08:00
}
2020-08-14 10:35:35 +08:00
if strings.HasPrefix(t, "map") {
tys, e := util.DecomposeType(t)
if e != nil {
log.Fatal(e)
2020-08-14 09:02:32 +08:00
}
2020-08-14 10:35:35 +08:00
if len(tys) != 2 {
2020-08-14 09:02:32 +08:00
log.Fatal("Map type number !=2")
}
2020-08-14 10:35:35 +08:00
return "Map<String," + parseType(tys[1]) + ">"
2020-08-14 09:02:32 +08:00
}
switch t {
case "string":
return "String"
case "int", "int32", "int64":
return "Int"
case "float", "float32", "float64":
return "Double"
case "bool":
return "Boolean"
default:
return t
}
}
2020-08-14 10:35:35 +08:00
func add(a, i int) int {
return a + i
}
2020-08-14 19:19:04 +08:00
func upperCase(s string) string {
return strings.ToUpper(s)
}