github.com/unionj-cloud/go-doudou@v1.3.8-0.20221011095552-0088008e5b31/cmd/internal/svc/codegen/main.go (about) 1 package codegen 2 3 import ( 4 "bufio" 5 "github.com/sirupsen/logrus" 6 "github.com/unionj-cloud/go-doudou/cmd/internal/astutils" 7 "github.com/unionj-cloud/go-doudou/version" 8 "os" 9 "path/filepath" 10 "strings" 11 "text/template" 12 ) 13 14 var mainTmpl = `/** 15 * Generated by go-doudou {{.Version}}. 16 * You can edit it as your need. 17 */ 18 package main 19 20 import ( 21 ddhttp "github.com/unionj-cloud/go-doudou/framework/http" 22 {{.ServiceAlias}} "{{.ServicePackage}}" 23 "{{.ConfigPackage}}" 24 "{{.HttpPackage}}" 25 ) 26 27 func main() { 28 conf := config.LoadFromEnv() 29 svc := {{.ServiceAlias}}.New{{.SvcName}}(conf) 30 handler := httpsrv.New{{.SvcName}}Handler(svc) 31 srv := ddhttp.NewHttpRouterSrv() 32 srv.AddRoute(httpsrv.Routes(handler)...) 33 srv.Run() 34 } 35 ` 36 37 // GenMain generates main function 38 func GenMain(dir string, ic astutils.InterfaceCollector) { 39 var ( 40 err error 41 modfile string 42 modName string 43 mainfile string 44 firstLine string 45 f *os.File 46 tpl *template.Template 47 cmdDir string 48 svcName string 49 alias string 50 ) 51 cmdDir = filepath.Join(dir, "cmd") 52 if err = MkdirAll(cmdDir, os.ModePerm); err != nil { 53 panic(err) 54 } 55 56 svcName = ic.Interfaces[0].Name 57 alias = ic.Package.Name 58 mainfile = filepath.Join(cmdDir, "main.go") 59 if _, err = Stat(mainfile); os.IsNotExist(err) { 60 modfile = filepath.Join(dir, "go.mod") 61 if f, err = Open(modfile); err != nil { 62 panic(err) 63 } 64 reader := bufio.NewReader(f) 65 firstLine, _ = reader.ReadString('\n') 66 modName = strings.TrimSpace(strings.TrimPrefix(firstLine, "module")) 67 68 if f, err = Create(mainfile); err != nil { 69 panic(err) 70 } 71 defer f.Close() 72 73 if tpl, err = template.New("main.go.tmpl").Parse(mainTmpl); err != nil { 74 panic(err) 75 } 76 if err = tpl.Execute(f, struct { 77 ServicePackage string 78 ConfigPackage string 79 HttpPackage string 80 SvcName string 81 ServiceAlias string 82 Version string 83 }{ 84 ServicePackage: modName, 85 ConfigPackage: modName + "/config", 86 HttpPackage: modName + "/transport/httpsrv", 87 SvcName: svcName, 88 ServiceAlias: alias, 89 Version: version.Release, 90 }); err != nil { 91 panic(err) 92 } 93 } else { 94 logrus.Warnf("file %s already exists", mainfile) 95 } 96 }