-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathsword.go
269 lines (218 loc) · 5.3 KB
/
sword.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
package gosword
import (
"compress/gzip"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"strconv"
"strings"
assetfs "github.com/elazarl/go-bindata-assetfs"
_ "github.com/go-sql-driver/mysql"
"github.com/sunshinev/go-sword/v2/assets/resource"
"github.com/sunshinev/go-sword/v2/assets/view"
"github.com/sunshinev/go-sword/v2/config"
)
type gZipWriter struct {
gz *gzip.Writer
http.ResponseWriter
}
func (u *gZipWriter) Write(p []byte) (int, error) {
return u.gz.Write(p)
}
type Sword struct {
}
func init() {
log.SetFlags(log.Ldate | log.Llongfile)
}
func Init(configFile string) *Sword {
// 初始化配置
err := config.LoadConfig(configFile)
if err != nil {
log.Fatalf("sword init err %v", err)
}
return &Sword{}
}
func (s *Sword) Run() {
h := http.NewServeMux()
// 数据表列表
h.HandleFunc("/api/model/table_list", s.handleError(s.tableList))
// 预览
h.HandleFunc("/api/model/preview", s.handleError(s.Preview))
// 创建生成文件
h.HandleFunc("/api/model/generate", s.handleError(s.Generate))
h.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// 静态文件路由
fs := assetfs.AssetFS{
Asset: resource.Asset,
AssetDir: resource.AssetDir,
AssetInfo: resource.AssetInfo,
Prefix: "resource/dist",
}
handle := http.FileServer(&fs)
w.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(w)
newWriter := &gZipWriter{
gz: gz,
ResponseWriter: w,
}
defer gz.Close()
handle.ServeHTTP(newWriter, r)
})
// Render vue component
h.HandleFunc("/render", s.handleError(s.Render))
s.Welcome()
go func() {
//Start server
err := http.ListenAndServe(":"+config.GlobalConfig.ServerPort, h)
if err != nil {
log.Fatalf("Go-sword start err: %v", err)
}
}()
}
func (s *Sword) handleError(h func(w http.ResponseWriter, r *http.Request) error) func(w http.ResponseWriter,
r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Printf("panic %v", err)
}
}()
err := h(w, r)
if err != nil {
w.Write([]byte(err.Error()))
}
}
}
type GenerateParams struct {
TableName string `json:"table_name"`
Files []string `json:"files"`
}
// Get database table list
func (s *Sword) tableList(w http.ResponseWriter, r *http.Request) error {
rows, err := config.GlobalConfig.DbConn.Query("SHOW TABLES")
if err != nil {
return err
}
tables := []string{}
for rows.Next() {
var tableName string
err = rows.Scan(&tableName)
tables = append(tables, tableName)
}
jsonData, err := json.Marshal(Ret{
Code: http.StatusOK,
Data: List{
List: tables,
},
})
_, err = w.Write(jsonData)
if err != nil {
return err
}
return nil
}
func (s *Sword) Preview(w http.ResponseWriter, r *http.Request) error {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
var data map[string]string
err = json.Unmarshal(body, &data)
if err != nil {
return err
}
if data["table_name"] == "" {
return errors.New("tableName is empty")
}
g := Generator{}.Init()
g.Preview(data["table_name"])
ret, err := json.Marshal(Ret{
Code: http.StatusOK,
Data: List{
List: &g.FileList,
},
})
if err != nil {
return err
}
_, err = w.Write(ret)
if err != nil {
return err
}
return nil
}
func (s *Sword) Generate(w http.ResponseWriter, r *http.Request) error {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
var data = &GenerateParams{}
err = json.Unmarshal(body, &data)
if err != nil {
return err
}
if data.TableName == "" {
return errors.New("tableName is empty")
}
if len(data.Files) == 0 {
return errors.New("Files is empty")
}
g := Generator{}.Init()
g.Generate(data.TableName, data.Files)
ret, err := json.Marshal(Ret{
Code: http.StatusOK,
Data: List{
List: &g.GFileList,
},
})
_, err = w.Write(ret)
if err != nil {
return err
}
return nil
}
func (s *Sword) Render(writer http.ResponseWriter, request *http.Request) error {
// 解析参数,映射到文件
err := request.ParseForm()
if err != nil {
return err
}
path := request.FormValue("path")
if path == "" {
return errors.New("lose path param")
}
// 从view目录中寻找文件
// body,err := ioutil.ReadFile("view/"+path+".html")
// 这里使用go-bindata释放到views目录,通过go文件加载资源,少了文件读写;使用bindata每次修改完html文件之后,需要重新生成views资源
body, err := view.Asset("view" + path + ".html")
if err != nil {
return err
}
_, err = writer.Write(body)
if err != nil {
return err
}
return nil
}
func (s *Sword) Welcome() {
c := config.GlobalConfig
str := "\nSTART----------------------------------------\n" +
"Go-Sword will create new project named " + c.
RootPath + " in current directory" +
"\n[Server info]" +
"\nServer port : " + c.ServerPort +
"\nProject module : " + c.RootPath +
"\n[db info]" +
"\nMySQL host : " + c.DatabaseSet.Host +
"\nMySQL port : " + strconv.Itoa(c.DatabaseSet.Port) +
"\nMySQL user : " + c.DatabaseSet.User +
"\nMySQL password : " + c.DatabaseSet.Password +
"\n\nStart successful, server is running ...\n" +
"Please request: " +
strings.Join([]string{"http://localhost:", c.ServerPort}, "") +
"\nEND----------------------------------------\n"
fmt.Println(str)
}