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

84 lines
1.7 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"
2020-08-08 16:40:10 +08:00
"github.com/tal-tech/go-zero/tools/goctl/util"
2020-07-29 17:11:41 +08:00
"github.com/urfave/cli"
)
const apiTemplate = `
syntax = "v1"
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 := util.CreateIfNotExist(apiFile)
if err != nil {
return err
}
defer fp.Close()
2021-09-07 10:16:10 +08:00
home := c.String("home")
if len(home) > 0 {
util.RegisterGoctlHome(home)
}
text, err := util.LoadTemplate(category, apiTemplateFile, apiTemplate)
if err != nil {
return err
}
2020-07-29 17:11:41 +08:00
baseName := util.FileNameWithoutExt(filepath.Base(apiFile))
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
}