go-zero/tools/goctl/api/apigen/gen.go

93 lines
1.9 KiB
Go
Raw Normal View History

2020-07-29 17:11:41 +08:00
package apigen
import (
"errors"
"fmt"
"path/filepath"
"strings"
"text/template"
"github.com/logrusorgru/aurora"
"github.com/urfave/cli"
"github.com/zeromicro/go-zero/tools/goctl/util"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
2020-07-29 17:11:41 +08:00
)
const apiTemplate = `
syntax = "v1"
2022-02-13 13:17:19 +08:00
info (
2020-07-29 17:11:41 +08:00
title: // TODO: add title
desc: // TODO: add description
author: "{{.gitUser}}"
email: "{{.gitEmail}}"
2020-07-29 17:11:41 +08:00
)
type request {
2020-07-29 17:11:41 +08:00
// TODO: add members here and delete this comment
}
type response {
2020-07-29 17:11:41 +08:00
// TODO: add members here and delete this comment
}
service {{.serviceName}} {
@handler GetUser // TODO: set handler name and delete this comment
get /users/id/:userId(request) returns(response)
2020-07-29 17:11:41 +08:00
@handler CreateUser // TODO: set handler name and delete this comment
post /users/create(request)
2020-07-29 17:11:41 +08:00
}
`
2021-02-20 19:50:03 +08:00
// ApiCommand create api template file
2020-07-29 17:11:41 +08:00
func ApiCommand(c *cli.Context) error {
apiFile := c.String("o")
if len(apiFile) == 0 {
return errors.New("missing -o")
}
fp, err := pathx.CreateIfNotExist(apiFile)
2020-07-29 17:11:41 +08:00
if err != nil {
return err
}
defer fp.Close()
2021-09-07 10:16:10 +08:00
home := c.String("home")
remote := c.String("remote")
if len(remote) > 0 {
repo, _ := util.CloneIntoGitHome(remote)
if len(repo) > 0 {
home = repo
}
}
2021-09-07 10:16:10 +08:00
if len(home) > 0 {
pathx.RegisterGoctlHome(home)
2021-09-07 10:16:10 +08:00
}
text, err := pathx.LoadTemplate(category, apiTemplateFile, apiTemplate)
2021-09-07 10:16:10 +08:00
if err != nil {
return err
}
baseName := pathx.FileNameWithoutExt(filepath.Base(apiFile))
2020-07-29 17:11:41 +08:00
if strings.HasSuffix(strings.ToLower(baseName), "-api") {
baseName = baseName[:len(baseName)-4]
} else if strings.HasSuffix(strings.ToLower(baseName), "api") {
baseName = baseName[:len(baseName)-3]
}
2021-09-07 10:16:10 +08:00
t := template.Must(template.New("etcTemplate").Parse(text))
2020-07-29 17:11:41 +08:00
if err := t.Execute(fp, map[string]string{
"gitUser": getGitName(),
"gitEmail": getGitEmail(),
"serviceName": baseName + "-api",
}); err != nil {
return err
}
fmt.Println(aurora.Green("Done."))
return nil
}