go-zero/tools/goctl/api/gogen/genetc.go

62 lines
1.3 KiB
Go
Raw Normal View History

2020-07-29 17:11:41 +08:00
package gogen
import (
"bytes"
"fmt"
"strconv"
"text/template"
2020-08-08 16:40:10 +08:00
"github.com/tal-tech/go-zero/tools/goctl/api/spec"
"github.com/tal-tech/go-zero/tools/goctl/api/util"
2020-10-15 16:36:49 +08:00
"github.com/tal-tech/go-zero/tools/goctl/templatex"
2020-07-29 17:11:41 +08:00
)
const (
defaultPort = 8888
etcDir = "etc"
etcTemplate = `Name: {{.serviceName}}
Host: {{.host}}
Port: {{.port}}
`
2020-07-29 17:11:41 +08:00
)
func genEtc(dir string, api *spec.ApiSpec) error {
fp, created, err := util.MaybeCreateFile(dir, etcDir, fmt.Sprintf("%s.yaml", api.Service.Name))
2020-07-29 17:11:41 +08:00
if err != nil {
return err
}
if !created {
return nil
}
defer fp.Close()
service := api.Service
host, ok := util.GetAnnotationValue(service.Annotations, "server", "host")
if !ok {
host = "0.0.0.0"
}
port, ok := util.GetAnnotationValue(service.Annotations, "server", "port")
if !ok {
port = strconv.Itoa(defaultPort)
}
2020-10-15 16:36:49 +08:00
text, err := templatex.LoadTemplate(category, etcTemplateFile, etcTemplate)
if err != nil {
return err
}
t := template.Must(template.New("etcTemplate").Parse(text))
2020-07-29 17:11:41 +08:00
buffer := new(bytes.Buffer)
err = t.Execute(buffer, map[string]string{
"serviceName": service.Name,
"host": host,
"port": port,
})
if err != nil {
return err
}
formatCode := formatCode(buffer.String())
_, err = fp.WriteString(formatCode)
return err
}