You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/tools/goctl/api/apigen/gen.go

93 lines
1.9 KiB
Go

4 years ago
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"
4 years ago
)
const apiTemplate = `
syntax = "v1"
info (
4 years ago
title: // TODO: add title
desc: // TODO: add description
author: "{{.gitUser}}"
email: "{{.gitEmail}}"
4 years ago
)
type request {
4 years ago
// TODO: add members here and delete this comment
}
type response {
4 years ago
// 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)
4 years ago
@handler CreateUser // TODO: set handler name and delete this comment
post /users/create(request)
4 years ago
}
`
// ApiCommand create api template file
4 years ago
func ApiCommand(c *cli.Context) error {
apiFile := c.String("o")
if len(apiFile) == 0 {
return errors.New("missing -o")
}
fp, err := pathx.CreateIfNotExist(apiFile)
4 years ago
if err != nil {
return err
}
defer fp.Close()
home := c.String("home")
remote := c.String("remote")
if len(remote) > 0 {
repo, _ := util.CloneIntoGitHome(remote)
if len(repo) > 0 {
home = repo
}
}
if len(home) > 0 {
pathx.RegisterGoctlHome(home)
}
text, err := pathx.LoadTemplate(category, apiTemplateFile, apiTemplate)
if err != nil {
return err
}
baseName := pathx.FileNameWithoutExt(filepath.Base(apiFile))
4 years ago
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]
}
t := template.Must(template.New("etcTemplate").Parse(text))
4 years ago
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
}