/
gen_api.go
62 lines (48 loc) · 1000 Bytes
/
gen_api.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package main
import (
"io/ioutil"
"log"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
type apiGen struct {
BaseGen
}
func NewApiGen(conf *viper.Viper) *apiGen {
g := new(apiGen)
g.Init(conf)
return g
}
func (d *apiGen) Gen() (err error) {
name := camelString(d.Filename)
if len(name) < 2 {
log.Fatalln("the filename length is greater than at least 2")
}
data := ApiTmplData{
Package: getPkgNameByFile(d.File),
LName: lcFirst(name),
OName: d.Filename,
}
content := ExecuteTemplate(ApiTemplate, data)
err = ioutil.WriteFile(d.File, []byte(content), 0644)
if err != nil {
return err
}
gofmt(d.File)
return nil
}
func genApiCmd() *cobra.Command {
var cmd = &cobra.Command{
Use: "gen-api",
Short: "Gen api code",
Run: func(cmd *cobra.Command, args []string) {
s := NewApiGen(Conf)
err := s.Gen()
if err != nil {
log.Fatalln(err)
}
},
}
cmd.Flags().StringP("file", "f", getGoFile(), "file path,eg. ./ab_c.go")
return cmd
}