代码拉取完成,页面将自动刷新
package api
import (
"bufio"
"errors"
"fmt"
"gitee.com/mosache/YFrame/core/common/slicex"
"gitee.com/mosache/YFrame/tools/Y/utils/cobraErr"
"gitee.com/mosache/YFrame/tools/Y/utils/gomodx"
"gitee.com/mosache/YFrame/tools/Y/vars"
"github.com/logrusorgru/aurora"
"github.com/spf13/cobra"
"html/template"
"io"
"os"
"strings"
)
const (
baseFileTemp = `syntax = "v1"
{{range .apiFiles -}}
import "{{.}}"
{{end}}
`
apiTemp = `syntax = "v1"
type (
DemoReq {}
DemoResp {}
)
@server (
middleware: Token
group: {{.apiName}}
prefix: /api
)
service {{.modName}}-api {
@doc "demo"
@handler demoHandler
post /demo (DemoReq) returns (DemoResp)
}
`
)
var apiCreateCmd = &cobra.Command{Use: "create",
Short: "create api file",
Long: `create api file with name`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
fileName := args[0]
if err := apiFileCreate(fileName); err != nil {
cobraErr.Err(cmd, err.Error())
}
},
}
func apiFileCreate(fileName string) error {
var (
baseApiFile *os.File
err error
)
if !gomodx.InProjectRoot() {
return errors.New("pls run Y api create cmd in root")
}
/// read base.api
baseApiFilePath := fmt.Sprintf("%s/%s", vars.ApiFileDir, vars.ApiBaseFile)
if baseApiFile, err = os.OpenFile(baseApiFilePath, os.O_RDWR, os.ModePerm); err != nil {
return err
}
reader := bufio.NewReader(baseApiFile)
var (
content []byte
)
apiFileArray := make([]string, 0)
for err != io.EOF {
content, _, err = reader.ReadLine()
baseFileContent := string(content)
baseFileContent = strings.TrimSpace(baseFileContent)
if strings.Contains(baseFileContent, "import") && len(baseFileContent) > 0 {
apiFileArray = append(apiFileArray,
strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(baseFileContent, "import", ""), " ", ""), "\"", ""))
}
}
if slicex.Contains(apiFileArray, fmt.Sprintf("%s.api", fileName)) {
return errors.New("fileName has already exist")
}
apiFileArray = append(apiFileArray, fmt.Sprintf("%s.api", fileName))
var (
t *template.Template
)
if t, err = template.New("baseT").Parse(baseFileTemp); err != nil {
return err
}
if baseApiFile, err = os.OpenFile(baseApiFilePath, os.O_RDWR|os.O_TRUNC, os.ModePerm); err != nil {
return err
}
if err = t.Execute(baseApiFile, map[string]interface{}{"apiFiles": apiFileArray}); err != nil {
return err
}
/// api file
var (
apiFile *os.File
)
apiFilePath := fmt.Sprintf("%s/%s", vars.ApiFileDir, fmt.Sprintf("%s.api", fileName))
if t, err = template.New("apiT").Parse(apiTemp); err != nil {
return err
}
if apiFile, err = os.OpenFile(apiFilePath, os.O_RDWR|os.O_CREATE, os.ModePerm); err != nil {
return err
}
if err = t.Execute(apiFile, map[string]any{"apiName": fileName, "modName": gomodx.GoModName()}); err != nil {
return err
}
fmt.Println(aurora.Green("DONE!"))
return nil
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。