New flags! Added verbs flag "-v" to autoapi to limit the generated verbs for an auto gen api. Defaults to "get". Added "listening address" flag "-l" to the generated api to change the binding address for the generated api's default main fn.

Olivier Tremblay 4 years ago
parent
commit
bc8849901c
4 changed files with 84 additions and 16 deletions
  1. 34 4
      lib/httpcodegenerator.go
  2. 3 3
      lib/libautoapi.go
  3. 38 3
      lib/maingenerator.go
  4. 9 6
      main.go

+ 34 - 4
lib/httpcodegenerator.go

@@ -6,6 +6,7 @@ import (
6 6
 	"go/format"
7 7
 	"io"
8 8
 	"os"
9
+	"strings"
9 10
 	"text/template"
10 11
 
11 12
 	"golang.org/x/tools/imports"
@@ -13,6 +14,7 @@ import (
13 14
 
14 15
 type httpCodeGenerator struct {
15 16
 	DbRootPackageName string
17
+	Verbs             string
16 18
 }
17 19
 
18 20
 func (g *httpCodeGenerator) Generate(tables map[string]tableInfo) error {
@@ -35,8 +37,8 @@ dbi "{{.dbiroot}}/{{.Table.TableName}}"
35 37
 "github.com/gorilla/mux"
36 38
 )
37 39
 
38
-
39
-
40
+{{$l := len .Table.PrimaryColumns}}
41
+{{if .shouldGenerateGet}}
40 42
 func List(res http.ResponseWriter, req *http.Request){
41 43
     enc := json.NewEncoder(res)
42 44
     
@@ -70,7 +72,7 @@ func List(res http.ResponseWriter, req *http.Request){
70 72
     enc.Encode(rows)
71 73
 }
72 74
 
73
-{{$l := len .Table.PrimaryColumns}}
75
+
74 76
 {{if gt $l 0}}
75 77
 func Get(res http.ResponseWriter, req *http.Request){
76 78
     vars := mux.Vars(req)
@@ -91,7 +93,9 @@ func Get(res http.ResponseWriter, req *http.Request){
91 93
     enc.Encode(row)
92 94
 }
93 95
 {{end}}
96
+{{end}}
94 97
 
98
+{{if .shouldGeneratePost}}
95 99
 func Post(res http.ResponseWriter, req *http.Request){
96 100
     err := save(req)
97 101
     if err != nil {
@@ -99,6 +103,9 @@ func Post(res http.ResponseWriter, req *http.Request){
99 103
         fmt.Fprint(res, err)
100 104
     }
101 105
 }
106
+{{end}}
107
+
108
+{{if .shouldGeneratePut}}
102 109
 {{if gt $l 0}}
103 110
 func Put(res http.ResponseWriter, req *http.Request){
104 111
     var err error
@@ -124,12 +131,16 @@ func Put(res http.ResponseWriter, req *http.Request){
124 131
     }
125 132
 }
126 133
 {{end}}
134
+{{end}}
135
+{{if or .shouldGeneratePut .shouldGeneratePost}}
127 136
 func save(req *http.Request) error {
128 137
     dec := json.NewDecoder(req.Body)
129 138
     row := &dbi.{{.Table.NormalizedTableName}}{}
130 139
     dec.Decode(&row)
131 140
     return {{.Table.TableName}}.Save(row)
132 141
 }
142
+{{end}}
143
+{{if .shouldGenerateDelete}}
133 144
 {{if gt $l 0}}
134 145
 func Delete(res http.ResponseWriter, req *http.Request){
135 146
     vars := mux.Vars(req)
@@ -144,6 +155,7 @@ func Delete(res http.ResponseWriter, req *http.Request){
144 155
     {{.Table.TableName}}.DeleteBy{{.Table.PrimaryColumnsJoinedByAnd}}(id)
145 156
 }
146 157
 {{end}}
158
+{{end}}
147 159
 `))
148 160
 
149 161
 	path, err := GetRootPath()
@@ -159,7 +171,16 @@ func Delete(res http.ResponseWriter, req *http.Request){
159 171
 			return err
160 172
 		}
161 173
 		var b bytes.Buffer
162
-		err = tmpl.Execute(&b, map[string]interface{}{"Table": tinfo, "DbRootPackageName": path + "/" + rootdbpath, "dbiroot": path + "/dbi"})
174
+		verbs := strings.Split(g.Verbs, ",")
175
+		err = tmpl.Execute(&b, map[string]interface{}{
176
+			"Table":                tinfo,
177
+			"DbRootPackageName":    path + "/" + rootdbpath,
178
+			"dbiroot":              path + "/dbi",
179
+			"shouldGenerateGet":    stringInSlice("get", verbs),
180
+			"shouldGeneratePost":   stringInSlice("post", verbs),
181
+			"shouldGeneratePut":    stringInSlice("put", verbs),
182
+			"shouldGenerateDelete": stringInSlice("delete", verbs),
183
+		})
163 184
 		if err != nil {
164 185
 			fmt.Println(b.String())
165 186
 			return err
@@ -184,3 +205,12 @@ func Delete(res http.ResponseWriter, req *http.Request){
184 205
 	tmpl = tmpl
185 206
 	return nil
186 207
 }
208
+
209
+func stringInSlice(a string, list []string) bool {
210
+	for _, b := range list {
211
+		if b == a {
212
+			return true
213
+		}
214
+	}
215
+	return false
216
+}

+ 3 - 3
lib/libautoapi.go

@@ -96,7 +96,7 @@ type fk struct {
96 96
 }
97 97
 
98 98
 //Generate grabs a sql connection, a database name, and generate all the required code to talk to the db.
99
-func Generate(db *sql.DB, dbName string) error {
99
+func Generate(db *sql.DB, dbName string, verbs string) error {
100 100
 	tables, err := getTableInfo(db, dbName)
101 101
 	if err != nil {
102 102
 		fmt.Println("failed getting table info")
@@ -112,7 +112,7 @@ func Generate(db *sql.DB, dbName string) error {
112 112
 		fmt.Println("failed generating db code")
113 113
 		return err
114 114
 	}
115
-	err = (&httpCodeGenerator{}).Generate(tables)
115
+	err = (&httpCodeGenerator{Verbs: verbs}).Generate(tables)
116 116
 	if err != nil {
117 117
 		fmt.Println("failed generating http code")
118 118
 		return err
@@ -128,7 +128,7 @@ func Generate(db *sql.DB, dbName string) error {
128 128
 		fmt.Println("failed generating swagger json")
129 129
 		return err
130 130
 	}
131
-	err = (&mainGenerator{}).Generate(tables)
131
+	err = (&mainGenerator{verbs: verbs}).Generate(tables)
132 132
 	if err != nil {
133 133
 		fmt.Println("failed generating maincode")
134 134
 		return err

+ 38 - 3
lib/maingenerator.go

@@ -7,6 +7,7 @@ import (
7 7
 	"html/template"
8 8
 	"io"
9 9
 	"os"
10
+	"strings"
10 11
 
11 12
 	"golang.org/x/tools/imports"
12 13
 )
@@ -14,6 +15,7 @@ import (
14 15
 type mainGenerator struct {
15 16
 	rootDbPackageName       string
16 17
 	rootHandlersPackageName string
18
+	verbs                   string
17 19
 }
18 20
 
19 21
 func (g *mainGenerator) Generate(tables map[string]tableInfo) error {
@@ -48,6 +50,7 @@ var (
48 50
 	dbName  string
49 51
 	dbUname string
50 52
 	dbPass  string
53
+	listenAddress string
51 54
 )
52 55
 
53 56
 func init() {
@@ -56,6 +59,7 @@ func init() {
56 59
 	flag.StringVar(&dbHost, "h", "localhost", "host")
57 60
 	flag.StringVar(&dbName, "d", "", "database name")
58 61
 	flag.StringVar(&dbUname, "u", "root", "username")
62
+	flag.StringVar(&listenAddress, "l", ":8080", "listening address")
59 63
 	flag.Parse()
60 64
 }
61 65
 
@@ -96,27 +100,48 @@ func main(){
96 100
     {{.TableName}}db.DB = dbConn
97 101
     {{end}}
98 102
     r := mux.NewRouter()
103
+{{$shouldGenerateGet := .shouldGenerateGet}}
104
+{{$shouldGeneratePost := .shouldGeneratePost}}
105
+{{$shouldGeneratePut := .shouldGeneratePut}}
106
+{{$shouldGenerateDelete := .shouldGenerateDelete}}
107
+{{if $shouldGenerateGet}}
99 108
     g := r.Methods("GET").Subrouter()
109
+{{end}}
110
+{{if $shouldGeneratePost}}
100 111
     po := r.Methods("POST").Subrouter()
112
+{{end}}
113
+{{if $shouldGeneratePut}}
101 114
     pu := r.Methods("PUT").Subrouter()
115
+{{end}}
116
+{{if $shouldGenerateDelete}}
102 117
     d := r.Methods("DELETE").Subrouter()
118
+{{end}}
103 119
 {{range .Tables}}
104 120
 {{$l := len .PrimaryColumns}}
105
-
121
+{{if $shouldGenerateGet}}
106 122
 g.HandleFunc("/{{.TableName}}", {{.TableName}}.List)
123
+{{end}}
124
+{{if $shouldGeneratePost}}
107 125
 po.HandleFunc("/{{.TableName}}", {{.TableName}}.Post)
126
+{{end}}
108 127
 {{if gt $l 0}}
128
+{{if $shouldGenerateGet}}
109 129
 g.HandleFunc("/{{.TableName}}/{id}", {{.TableName}}.Get)
130
+{{end}}
131
+{{if $shouldGeneratePut}}
110 132
 pu.HandleFunc("/{{.TableName}}/{id}", {{.TableName}}.Put)
133
+{{end}}
134
+{{if $shouldGenerateDelete}}
111 135
 d.HandleFunc("/{{.TableName}}/{id}", {{.TableName}}.Delete)
112 136
 {{end}}
137
+{{end}}
113 138
 
114 139
 
115 140
 {{end}}
116 141
 
117 142
 g.HandleFunc("/swagger.json", swaggerresponse)
118 143
 
119
-http.ListenAndServe(":8080",r)
144
+http.ListenAndServe(listenAddress,r)
120 145
 }
121 146
 `))
122 147
 	routestmpl = routestmpl
@@ -133,7 +158,15 @@ http.ListenAndServe(":8080",r)
133 158
 	var final bytes.Buffer
134 159
 	io.Copy(&final, &b)
135 160
 	b = bytes.Buffer{}
136
-	routestmpl.Execute(&b, map[string]interface{}{"Verbs": []string{"List", "Get", "Post", "Put", "Delete"}, "Tables": tables})
161
+	verbs := strings.Split(g.verbs, ",")
162
+	routestmpl.Execute(&b, map[string]interface{}{
163
+		"Verbs":                []string{"List", "Get", "Post", "Put", "Delete"},
164
+		"Tables":               tables,
165
+		"shouldGenerateGet":    stringInSlice("get", verbs),
166
+		"shouldGeneratePost":   stringInSlice("post", verbs),
167
+		"shouldGeneratePut":    stringInSlice("put", verbs),
168
+		"shouldGenerateDelete": stringInSlice("delete", verbs),
169
+	})
137 170
 	io.Copy(&final, &b)
138 171
 	f, err := os.Create("bin/main.go")
139 172
 	if err != nil && !os.IsExist(err) {
@@ -142,10 +175,12 @@ http.ListenAndServe(":8080",r)
142 175
 
143 176
 	formatted, err := format.Source(final.Bytes())
144 177
 	if err != nil {
178
+		io.Copy(f, bytes.NewBuffer(final.Bytes()))
145 179
 		return err
146 180
 	}
147 181
 	formatted, err = imports.Process(f.Name(), formatted, nil)
148 182
 	if err != nil {
183
+		io.Copy(f, bytes.NewBuffer(formatted))
149 184
 		return err
150 185
 	}
151 186
 	io.Copy(f, bytes.NewBuffer(formatted))

+ 9 - 6
main.go

@@ -26,14 +26,16 @@ var (
26 26
 	dbName  string
27 27
 	dbUname string
28 28
 	dbPass  string
29
+	verbs   string
29 30
 )
30 31
 
31 32
 func init() {
32
-	flag.StringVar(&dbPort, "P", "3306", "port")
33
-	flag.StringVar(&dbPass, "p", defaultPassValue, "password")
34
-	flag.StringVar(&dbHost, "h", "localhost", "host")
33
+	flag.StringVar(&dbPort, "P", "3306", "database port")
34
+	flag.StringVar(&dbPass, "p", defaultPassValue, "database password")
35
+	flag.StringVar(&dbHost, "h", "localhost", "database host")
35 36
 	flag.StringVar(&dbName, "d", "", "database name")
36
-	flag.StringVar(&dbUname, "u", "root", "username")
37
+	flag.StringVar(&dbUname, "u", "root", "database username")
38
+	flag.StringVar(&verbs, "v", "get", "HTTP verbs to handle.")
37 39
 	flag.Parse()
38 40
 }
39 41
 
@@ -70,8 +72,9 @@ func main() {
70 72
 		flag.PrintDefaults()
71 73
 		log.Panic(err)
72 74
 	}
73
-	err = lib.Generate(dbConn, dbName)
75
+	verbs = strings.ToLower(verbs)
76
+	err = lib.Generate(dbConn, dbName, verbs)
74 77
 	if err != nil {
75
-		log.Panic(err)
78
+		panic(err)
76 79
 	}
77 80
 }