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/gogen/genconfig.go

70 lines
1.4 KiB
Go

4 years ago
package gogen
import (
"bytes"
4 years ago
"fmt"
"strings"
4 years ago
"text/template"
"github.com/tal-tech/go-zero/tools/goctl/api/spec"
"github.com/tal-tech/go-zero/tools/goctl/api/util"
ctlutil "github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/tal-tech/go-zero/tools/goctl/vars"
4 years ago
)
const (
configFile = "config.go"
configTemplate = `package config
import {{.authImport}}
4 years ago
type Config struct {
rest.RestConf
{{.auth}}
4 years ago
}
`
jwtTemplate = ` struct {
AccessSecret string
AccessExpire int64
}
4 years ago
`
)
func genConfig(dir string, api *spec.ApiSpec) error {
4 years ago
fp, created, err := util.MaybeCreateFile(dir, configDir, configFile)
if err != nil {
return err
}
if !created {
return nil
}
defer fp.Close()
var authNames = getAuths(api)
var auths []string
for _, item := range authNames {
auths = append(auths, fmt.Sprintf("%s %s", item, jwtTemplate))
}
4 years ago
var authImportStr = fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceUrl)
text, err := ctlutil.LoadTemplate(category, configTemplateFile, configTemplate)
if err != nil {
return err
}
t := template.Must(template.New("configTemplate").Parse(text))
4 years ago
buffer := new(bytes.Buffer)
err = t.Execute(buffer, map[string]string{
"authImport": authImportStr,
"auth": strings.Join(auths, "\n"),
4 years ago
})
if err != nil {
return err
4 years ago
}
4 years ago
formatCode := formatCode(buffer.String())
_, err = fp.WriteString(formatCode)
return err
}