forked from mojocn/felix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtpl_data.go
2039 lines (1821 loc) · 48 KB
/
tpl_data.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package ginbro
var tDocYaml = tplNode{
NameFormat: "doc/swagger.yaml",
TplContent: `swagger: "2.0"
info:
description: "A GinBro RESTful APIs"
version: "1.0.0"
title: "GinBro RESTful APIs Application"
host: "{{.AppAddr}}"
basePath: "/api/v1"
schemes:
- "http"
paths:
{{range .Resources}}
{{if .IsAuthTable}}
/login:
post:
tags:
- "auth"
summary: "login by {{.ResourceName}}"
description: "login by {{.ResourceName}}"
consumes:
- "application/json"
produces:
- "application/json"
parameters:
- in: "body"
name: "body"
description: "create {{.ResourceName}}"
required: true
schema:
$ref: "#/definitions/{{.ModelName}}"
responses:
200:
description: "successful operation"
schema:
$ref: "#/definitions/{{.ModelName}}Auth"
{{end}}
/{{.ResourceName}}:
get:
tags:
- "{{.ResourceName}}"
summary: "get all {{.ResourceName}} by pagination"
description: ""
consumes:
- "application/json"
produces:
- "application/json"
parameters:
- name: "where"
in: "query"
description: "column:value will use sql LIKE for search eg:id:67 will where id >67 eg2: name:eric => where name LIKE '%eric%'"
required: false
type: "array"
items:
type: "string"
- name: "fields"
in: "query"
description: "{$tableColumn},{$tableColumn}... "
required: false
type: "string"
- name: "order"
in: "query"
description: "eg: id desc, name desc"
required: false
type: "string"
- name: "offset"
in: "query"
description: "sql offset eg: 10"
required: false
type: "integer"
- name: "limit"
in: "query"
default: "2"
description: "limit returning object count"
required: false
type: "integer"
responses:
200:
description: "successful operation"
schema:
type: "array"
items:
$ref: "#/definitions/{{.ModelName}}Pagination"
post:
tags:
- "{{.ResourceName}}"
summary: "create {{.ResourceName}}"
description: "create {{.ResourceName}}"
consumes:
- "application/json"
produces:
- "application/json"
parameters:
- in: "body"
name: "body"
description: "create {{.ResourceName}}"
required: true
schema:
$ref: "#/definitions/{{.ModelName}}"
responses:
200:
description: "successful operation"
schema:
$ref: "#/definitions/ApiResponse"
patch:
tags:
- "{{.ResourceName}}"
summary: "update {{.ResourceName}}"
description: "update {{.ResourceName}}"
consumes:
- "application/json"
produces:
- "application/json"
parameters:
- in: "body"
name: "body"
description: "create {{.ResourceName}}"
required: true
schema:
$ref: "#/definitions/{{.ModelName}}"
responses:
200:
description: "successful operation"
schema:
$ref: "#/definitions/ApiResponse"
/{{.ResourceName}}/{Id}:
get:
tags:
- "{{.ResourceName}}"
summary: "get a {{.ResourceName}} by ID"
description: "get a {{.ResourceName}} by ID"
consumes:
- "application/json"
produces:
- "application/json"
parameters:
- name: "Id"
in: "path"
description: "ID of {{.ResourceName}} to return"
required: true
type: "integer"
format: "int64"
responses:
200:
description: "successful operation"
schema:
$ref: "#/definitions/{{.ModelName}}"
delete:
tags:
- "{{.ResourceName}}"
summary: "Destroy a {{.ResourceName}} by ID"
description: "delete a {{.ResourceName}} by ID"
consumes:
- "application/json"
produces:
- "application/json"
parameters:
- name: "Id"
in: "path"
description: "ID of {{.ResourceName}} to delete"
required: true
type: "integer"
format: "int64"
responses:
200:
description: "successful operation"
schema:
$ref: "#/definitions/ApiResponse"
{{end}}
definitions:
{{range $table := .Resources}}
{{ if $table.IsAuthTable }}
{{$table.ModelName}}Auth:
type: "object"
properties:
{{range $row := $table.Properties}}
{{$row.ColumnName}}:
type: "{{$row.SwaggerType}}"
description: "{{$row.ColumnComment}}"
format: "{{$row.SwaggerFormat}}"
{{end}}
token:
type: "string"
description: "jwt token"
format: "string"
expire:
type: "string"
description: "jwt token expire time"
format: "date-time"
expire_ts:
type: "integer"
description: "expire timestamp unix"
format: "int64"
{{end}}
{{$table.ModelName}}:
type: "object"
properties:
{{range $row := $table.Properties}}
{{$row.ColumnName}}:
type: "{{$row.SwaggerType}}"
description: "{{$row.ColumnComment}}"
format: "{{$row.SwaggerFormat}}"
{{end}}
{{$table.ModelName}}Pagination:
type: "object"
properties:
code:
type: "integer"
description: "json repose code"
format: "int32"
total:
type: "integer"
description: "total numbers"
format: "int32"
offset:
type: "integer"
description: "offset"
format: "int32"
limit:
type: "integer"
description: "limit"
format: "int32"
list:
type: "array"
items:
$ref: "#/definitions/{{$table.ModelName}}"
{{end}}
ApiResponse:
type: "object"
properties:
code:
type: "integer"
format: "int32"
msg:
type: "string"
externalDocs:
description: "Find out more about Swagger"
url: "http://swagger.io"
`,
}
var tReadme = tplNode{
NameFormat: "readme.md",
TplContent: `
# A GinBro RESTful APIs
## Recommend Go version > 1.12
- for Chinese users: set env GOPROXY=https://goproxy.io
- run: go tidy
## Usage
- [swagger DOC ](http://{{.AppAddr}}/doc)_[BACKQUOTE]_http://{{.AppAddr}}/swagger/_[BACKQUOTE]_
- [static ](http://{{.AppAddr}})_[BACKQUOTE]_http://{{.AppAddr}}_[BACKQUOTE]_
- [GinbroApp INFO ](http://{{.AppAddr}}/GinbroApp/info)_[BACKQUOTE]_http://{{.AppAddr}}/GinbroApp/info_[BACKQUOTE]_
- API baseURL : _[BACKQUOTE]_http://{{.AppAddr}}/api/v1_[BACKQUOTE]_
## Info
- table'schema which has no "ID","id","Id" or "iD" will not generate model or route.
- the column which type is json value must be a string which is able to decode to a JSON,when call POST or PATCH.
## Thanks
- [swagger Specification](https://swagger.io/specification/)
- [gin-gonic/gin](https://github.com/gin-gonic/gin)
- [GORM](http://gorm.io/)
- [viper](https://github.com/spf13/viper)
- [cobra](https://github.com/spf13/cobra#getting-started)
- [go-redis](https://go get github.com/go-redis/redis)
`,
}
var tModelObj = tplNode{
NameFormat: "models/m_%s.go",
TplContent: `
package models
import (
"errors"
"time"
{{if .IsAuthTable}}"fmt"
"{{.AppPkg}}/config"
"golang.org/x/crypto/bcrypt"
"github.com/sirupsen/logrus"
{{end}}
)
var _ = time.Thursday
//{{.ModelName}}
type {{.ModelName}} struct {
{{range .Properties}}
{{.ModelProp}} {{.ModelType}} _[BACKQUOTE]_{{.ModelTag}}_[BACKQUOTE]_{{end}}
}
//TableName
func (m *{{.ModelName}}) TableName() string {
return "{{.TableName}}"
}
//One
func (m *{{.ModelName}}) One() (one *{{.ModelName}}, err error) {
one = &{{.ModelName}}{}
err = crudOne(m, one)
return
}
//All
func (m *{{.ModelName}}) All(q *PaginationQuery) (list *[]{{.ModelName}}, total uint, err error) {
list = &[]{{.ModelName}}{}
total, err = crudAll(m, q, list)
return
}
//Update
func (m *{{.ModelName}}) Update() (err error) {
where := {{.ModelName}}{Id: m.Id}
m.Id = 0
{{if .IsAuthTable }}m.makePassword()
{{end}}
return crudUpdate(m, where)
}
//Create
func (m *{{.ModelName}}) Create() (err error) {
m.Id = 0
{{if .IsAuthTable }}m.makePassword()
{{end}}
return db.Create(m).Error
}
//Delete
func (m *{{.ModelName}}) Delete() (err error) {
if m.Id == 0 {
return errors.New("resource must not be zero value")
}
return crudDelete(m)
}
{{if .IsAuthTable }}
//Login
func (m *{{.ModelName}}) Login(ip string) (*jwtObj, error) {
m.Id = 0
if m.{{.PasswordPropertyName}} == "" {
return nil, errors.New("password is required")
}
inputPassword := m.{{.PasswordPropertyName}}
m.{{.PasswordPropertyName}} = ""
loginTryKey := "login:" + ip
loginRetries, _ := mem.GetUint(loginTryKey)
if loginRetries > uint(config.GetInt("GinbroApp.login_try")) {
memExpire := config.GetInt("GinbroApp.mem_expire_min")
return nil, fmt.Errorf("for too many wrong login retries the %s will ban for login in %d minitues", ip, memExpire)
}
//you can implement more detailed login retry rule
//for i don't know what your login username i can't implement the ip+username rule in my boilerplate project
// about username and ip retry rule
err := db.Where(m).First(&m).Error
if err != nil {
//username fail ip retries add 5
loginRetries = loginRetries + 5
mem.Set(loginTryKey, loginRetries)
return nil, err
}
//password is set to bcrypt check
if err := bcrypt.CompareHashAndPassword([]byte(m.{{.PasswordPropertyName}}), []byte(inputPassword)); err != nil {
// when password failed reties will add 1
loginRetries = loginRetries + 1
mem.Set(loginTryKey, loginRetries)
return nil, err
}
m.{{.PasswordPropertyName}} = ""
key := fmt.Sprintf("login:%d", m.Id)
//save login user into the memory store
data ,err := jwtGenerateToken(m)
mem.Set(key, data)
return data,err
}
func (m *{{.ModelName}}) makePassword() {
if m.{{.PasswordPropertyName}} != "" {
if bytes, err := bcrypt.GenerateFromPassword([]byte(m.{{.PasswordPropertyName}}), bcrypt.DefaultCost); err != nil {
logrus.WithError(err).Error("bcrypt making password is failed")
} else {
m.{{.PasswordPropertyName}} = string(bytes)
}
}
}
{{end}}
`,
}
var tModelJwt = tplNode{
NameFormat: "models/m_jwt.go",
TplContent: `
package models
import (
"errors"
"fmt"
"github.com/dgrijalva/jwt-go"
"github.com/sirupsen/logrus"
"{{.AppPkg}}/config"
"time"
)
func jwtGenerateToken(m *{{.ModelName}}) (*jwtObj, error) {
m.{{.PasswordPropertyName}} = ""
expireAfterTime := time.Hour * time.Duration(config.GetInt("GinbroApp.jwt_expire_hour"))
iss := config.GetString("GinbroApp.name")
appSecret := config.GetString("GinbroApp.secret")
expireTime := time.Now().Add(expireAfterTime)
stdClaims := jwt.StandardClaims{
ExpiresAt: expireTime.Unix(),
IssuedAt: time.Now().Unix(),
Id: fmt.Sprintf("%d", m.Id),
Issuer: iss,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, stdClaims)
// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString([]byte(appSecret))
if err != nil {
logrus.WithError(err).Fatal("config is wrong, can not generate jwt")
}
data := &jwtObj{ {{.ModelName}}: *m, Token: tokenString, Expire: expireTime, ExpireTs: expireTime.Unix()}
return data, err
}
type jwtObj struct {
{{.ModelName}}
Token string _[BACKQUOTE]_json:"token"_[BACKQUOTE]_
Expire time.Time _[BACKQUOTE]_json:"expire"_[BACKQUOTE]_
ExpireTs int64 _[BACKQUOTE]_json:"expire_ts"_[BACKQUOTE]_
}
//JwtParseUser
func JwtParseUser(tokenString string) (*{{.ModelName}}, error) {
if tokenString == "" {
return nil, errors.New("no token is found in Authorization Bearer")
}
claims := jwt.StandardClaims{}
_, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
secret := config.GetString("GinbroApp.secret")
return []byte(secret), nil
})
if err != nil {
return nil, err
}
if claims.VerifyExpiresAt(time.Now().Unix(), true) == false {
return nil, errors.New("token is expired")
}
appName := config.GetString("GinbroApp.name")
if !claims.VerifyIssuer(appName, true) {
return nil, errors.New("token's issuer is wrong,greetings Hacker")
}
key := fmt.Sprintf("login:%s", claims.Id)
jwtObj, err := mem.GetJwtObj(key)
if err != nil {
return nil, err
}
return &jwtObj.{{.ModelName}}, err
}
//GetJwtObj
func (s *memoryStore) GetJwtObj(id string) (value *jwtObj, err error) {
vv, err := s.Get(id, false)
if err != nil {
return nil, err
}
value, ok := vv.(*jwtObj)
if ok {
return value, nil
}
return nil, errors.New("mem:has value of this id, but is not type of *jwtObj")
}
`,
}
var tHandlersObj = tplNode{
NameFormat: "handlers/h_%s.go",
TplContent: `
package handlers
import (
"{{.AppPkg}}/models"
"github.com/gin-gonic/gin"
)
func init() {
groupApi.GET("{{.ResourceName}}",{{if .IsAuthTable}}jwtMiddleware,{{end}} {{.HandlerName}}All)
{{if .HasId}}groupApi.GET("{{.ResourceName}}/:id", {{if .IsAuthTable}}jwtMiddleware,{{end}} {{.HandlerName}}One){{end}}
groupApi.POST("{{.ResourceName}}", {{if .IsAuthTable}}jwtMiddleware,{{end}} {{.HandlerName}}Create)
groupApi.PATCH("{{.ResourceName}}", {{if .IsAuthTable}}jwtMiddleware,{{end}} {{.HandlerName}}Update)
{{if .HasId}}groupApi.DELETE("{{.ResourceName}}/:id", {{if .IsAuthTable}}jwtMiddleware,{{end}} {{.HandlerName}}Delete){{end}}
}
//All
func {{.HandlerName}}All(c *gin.Context) {
mdl := models.{{.ModelName}}{}
query := &models.PaginationQuery{}
err := c.ShouldBindQuery(query)
if handleError(c, err) {
return
}
list, total, err := mdl.All(query)
if handleError(c, err) {
return
}
jsonPagination(c, list, total, query)
}
{{if .HasId}}
//One
func {{.HandlerName}}One(c *gin.Context) {
var mdl models.{{.ModelName}}
id, err := parseParamID(c)
if handleError(c, err) {
return
}
mdl.Id = id
data, err := mdl.One()
if handleError(c, err) {
return
}
jsonData(c, data)
}
{{end}}
//Create
func {{.HandlerName}}Create(c *gin.Context) {
var mdl models.{{.ModelName}}
err := c.ShouldBind(&mdl)
if handleError(c, err) {
return
}
err = mdl.Create()
if handleError(c, err) {
return
}
jsonData(c, mdl)
}
//Update
func {{.HandlerName}}Update(c *gin.Context) {
var mdl models.{{.ModelName}}
err := c.ShouldBind(&mdl)
if handleError(c, err) {
return
}
err = mdl.Update()
if handleError(c, err) {
return
}
jsonSuccess(c)
}
{{if .HasId}}
//Delete
func {{.HandlerName}}Delete(c *gin.Context) {
var mdl models.{{.ModelName}}
id, err := parseParamID(c)
if handleError(c, err) {
return
}
mdl.Id = id
err = mdl.Delete()
if handleError(c, err) {
return
}
jsonSuccess(c)
}
{{end}}
`,
}
var tStaticIndex = tplNode{
"static/index.html",
`
<!DOCTYPE html><html lang="en">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width">
<title>Golang+gin+gorm+sql created by felix ginbro</title>
<body>
<h2 style="text-align: center">put front end files into this folder</h2>
</body>
</html>
`,
}
var tHandlersObjBare = tplNode{
NameFormat: "handlers/h_%s.go",
TplContent: `
package handlers
import (
"github.com/gin-gonic/gin"
)
func init() {
groupApi.GET("{{.ResourceName}}",{{.HandlerName}}All)
groupApi.GET("{{.ResourceName}}/:id", {{.HandlerName}}One)
groupApi.POST("{{.ResourceName}}", {{.HandlerName}}Create)
groupApi.PATCH("{{.ResourceName}}", {{.HandlerName}}Update)
groupApi.DELETE("{{.ResourceName}}/:id", {{.HandlerName}}Delete)
}
//All
func {{.HandlerName}}All(c *gin.Context) {
}
//One
func {{.HandlerName}}One(c *gin.Context) {
}
//Create
func {{.HandlerName}}Create(c *gin.Context) {
}
//Update
func {{.HandlerName}}Update(c *gin.Context) {
}
//Delete
func {{.HandlerName}}Delete(c *gin.Context) {
}
`,
}
var tConfigToml = tplNode{
NameFormat: "config.toml",
TplContent: `
[GinbroApp]
name = "ginBro"
addr ="{{.AppAddr}}" # eg1: www.mojotv.cn eg:localhost:3333 eg1:127.0.0.1:88
secret = "{{.AppSecret}}"
env = "local" # only allows local/dev/test/prod
log_level = "error" # only allows debug info warn error fatal panic
enable_not_found = true # if true and static_path is not empty string, all not found route will serve static/index.html
enable_swagger = true
enable_cors = true # true will case 403 error in swaggerUI may cause api perform decrease
enable_sql_log = true # show gorm sql in terminal
enable_https = false # if addr is a domain enable_https will works
enable_cron = false # is enable buildin schedule job
time_zone = "Asia/Shanghai"
api_prefix = "v1" # api_prefix could be empty string, the api uri will be api/v1/resource
static_path = "./static/" # path must be an absolute path or relative to the go-build-executable file, may cause api perform decrease
mem_expire_min = 60 # memory cache expire in 60 minutes
mem_max_count = 1024000 # memory cache maxium store count
login_try = 100 # after 100 times login failure the IP will be ban for mem_expire_min(default 600min), wrong username costs 5 times, wrong password costs 1 time,
jwt_expire_hour = 24 # jwt expire in 24 hours
[db]
type = "{{.DbType}}"
addr = "{{.DbAddr}}"
user = "{{.DbUser}}"
password = "{{.DbPassword}}"
database = "{{.DbName}}"
charset = "{{.DbChar}}"
[redis]
addr = "" # 127.0.0.1:6379 empty string will not init the redis db in models package
password = ""
db_idx = 0
# the init config has not impelement yet
[init]
user_email= "admin@ginbro.com" # if not exist, create a user with the bcrypt password, if the value is empty will do nothing
user_password = "123123" # print the bcrypted password in console for you to paste into mysql auth_table.password column
`,
}
var tModelDbMem = tplNode{
NameFormat: "models/db_mem.go",
TplContent: `
package models
import (
"container/list"
"errors"
"github.com/sirupsen/logrus"
"{{.AppPkg}}/config"
"sync"
"time"
)
var mem *memoryStore
func init() {
mem = new(memoryStore)
mem.digitsById = make(map[string]interface{})
mem.idByTime = list.New()
maxCount := config.GetInt("GinbroApp.mem_max_count")
if maxCount <= 1024 {
maxCount = 1024
}
mem.collectNum = maxCount
expireIn := config.GetInt("GinbroApp.mem_expire_min")
if expireIn <= 0 {
expireIn = 30
}
mem.expiration = time.Minute * time.Duration(expireIn)
}
type idByTimeValue struct {
timestamp time.Time
id string
}
// memoryStore is an internal store for captcha ids and their values.
type memoryStore struct {
sync.RWMutex
digitsById map[string]interface{}
idByTime *list.List
// Number of items stored since last collection.
numStored int
// Number of saved items that triggers collection.
collectNum int
// Expiration time of captchas.
expiration time.Duration
}
func (s *memoryStore) Set(id string, value interface{}) {
s.Lock()
s.digitsById[id] = value
s.idByTime.PushBack(idByTimeValue{time.Now(), id})
s.numStored++
s.Unlock()
if s.numStored > s.collectNum {
go s.collect()
}
}
func (s *memoryStore) Get(id string, clear bool) (value interface{}, err error) {
if !clear {
// When we don't need to clear captcha, acquire read lock.
s.RLock()
defer s.RUnlock()
} else {
s.Lock()
defer s.Unlock()
}
value, ok := s.digitsById[id]
if !ok {
return nil, errors.New("value not found")
}
if clear {
delete(s.digitsById, id)
}
return
}
func (s *memoryStore) collect() {
logrus.Warn("memory store collect function has been called some value will be lost")
now := time.Now()
s.Lock()
defer s.Unlock()
s.numStored = 0
for e := s.idByTime.Front(); e != nil; {
ev, ok := e.Value.(idByTimeValue)
if !ok {
return
}
if ev.timestamp.Add(s.expiration).Before(now) {
delete(s.digitsById, ev.id)
next := e.Next()
s.idByTime.Remove(e)
e = next
} else {
return
}
}
}
func (s *memoryStore) GetUint(id string) (value uint, err error) {
vv, err := s.Get(id, false)
if err != nil {
return 0, err
}
value, ok := vv.(uint)
if ok {
return value, nil
}
return 0, errors.New("mem:has value of this id, but is not type of uint")
}
`,
}
var tModelHelper = tplNode{
NameFormat: "models/helper.go",
TplContent: `
package models
import (
"errors"
"fmt"
"github.com/jinzhu/gorm"
"reflect"
"strconv"
"strings"
)
//PaginationQuery gin handler query binding struct
type PaginationQuery struct {
Where string _[BACKQUOTE]_form:"where"_[BACKQUOTE]_
Fields string _[BACKQUOTE]_form:"fields"_[BACKQUOTE]_
Order string _[BACKQUOTE]_form:"order"_[BACKQUOTE]_
Offset uint _[BACKQUOTE]_form:"offset"_[BACKQUOTE]_
Limit uint _[BACKQUOTE]_form:"limit"_[BACKQUOTE]_
}
//String to string
func (pq *PaginationQuery) String() string {
return fmt.Sprintf("w=%v_f=%s_o=%s_of=%d_l=%d", pq.Where, pq.Fields, pq.Order, pq.Offset, pq.Limit)
}
func crudAll(m interface{}, q *PaginationQuery, list interface{}) (total uint, err error) {
var tx *gorm.DB
total, tx = getResourceCount(m, q)
if q.Fields != "" {
columns := strings.Split(q.Fields, ",")
if len(columns) > 0 {
tx = tx.Select(q.Fields)
}
}
if q.Order != "" {
tx = tx.Order(q.Order)
}
if q.Offset > 0 {
tx = tx.Offset(q.Offset)
}
if q.Limit <= 0 {
q.Limit = 15
}
err = tx.Limit(q.Limit).Find(list).Error
return
}
func crudOne(m interface{}, one interface{}) (err error) {
if db.Where(m).First(one).RecordNotFound() {
return errors.New("resource is not found")
}
return nil
}
func crudUpdate(m interface{}, where interface{}) (err error) {
db := db.Model(where).Updates(m)
if err = db.Error; err != nil {
return
}
if db.RowsAffected != 1 {
return errors.New("id is invalid and resource is not found")
}
return nil
}
func crudDelete(m interface{}) (err error) {
//WARNING When delete a record, you need to ensure it’s primary field has value, and GORM will use the primary key to delete the record, if primary field’s blank, GORM will delete all records for the model
//primary key must be not zero value
db := db.Delete(m)
if err = db.Error; err != nil {
return
}
if db.RowsAffected != 1 {
return errors.New("resource is not found to destroy")
}
return nil
}
func getResourceCount(m interface{}, q *PaginationQuery) (uint, *gorm.DB) {
var tx = db.Model(m)
conditions := strings.Split(q.Where, ",")
for _, val := range conditions {
w := strings.SplitN(val, ":", 2)
if len(w) == 2 {
bindKey, bindValue := w[0], w[1]
if intV, err := strconv.ParseInt(bindValue, 10, 64); err == nil {
// bind value is int
field := fmt.Sprintf("_[BACKQUOTE]_%s_[BACKQUOTE]_ > ?", bindKey)
tx = tx.Where(field, intV)
} else if fV, err := strconv.ParseFloat(bindValue, 64); err == nil {
// bind value is float
field := fmt.Sprintf("_[BACKQUOTE]_%s_[BACKQUOTE]_ > ?", bindKey)
tx = tx.Where(field, fV)
} else if bindValue != "" {
// bind value is string
field := fmt.Sprintf("_[BACKQUOTE]_%s_[BACKQUOTE]_ LIKE ?", bindKey)
sV := fmt.Sprintf("%%%s%%", bindValue)
tx = tx.Where(field, sV)
}
}
}
modelName := getType(m)
rKey := redisPrefix + modelName + q.String() + "_count"
v, err := mem.GetUint(rKey)
if err != nil {
var count uint
tx.Count(&count)
mem.Set(rKey, count)
return count, tx
}
return v, tx
}
func getType(v interface{}) string {
t := reflect.TypeOf(v)
if t.Kind() == reflect.Ptr {
return "*" + t.Elem().Name()
}
return t.Name()
}
`,
}
var tModelDbSql = tplNode{
NameFormat: "models/db_sql.go",
TplContent: `
package models
import (
"fmt"
"github.com/go-redis/redis"
_ "github.com/jinzhu/gorm/dialects/mssql"
_ "github.com/jinzhu/gorm/dialects/mysql"
_ "github.com/jinzhu/gorm/dialects/postgres"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"github.com/jinzhu/gorm"
"github.com/sirupsen/logrus"
"{{.AppPkg}}/config"
"strings"
"errors"
)
//redis client
var redisDB *redis.Client
var db *gorm.DB
const redisPrefix = "ginbro:"
func init() {
//initializing redis client
redisAddr, redisPassword := config.GetString("redis.addr"), config.GetString("redis.password")
if redisAddr != "" {
redisDB = redis.NewClient(&redis.Options{
Addr: redisAddr,
Password: redisPassword, // no password set
DB: config.GetInt("redis.db_idx"), // use default DB
})
if pong, err := redisDB.Ping().Result(); err != nil || pong != "PONG" {
logrus.WithError(err).Fatal("could not connect to the redis server")
}
}
if gormDB, err := createDatabase(); err == nil {
db = gormDB
} else {
logrus.WithError(err).Fatalln("create database connection failed")
}
//enable Gorm mysql log
if flag := config.GetBool("GinbroApp.enable_sql_log"); flag {
db.LogMode(flag)
//f, err := os.OpenFile("mysql_gorm.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
//if err != nil {
// logrus.WithError(err).Fatalln("could not create mysql gorm log file")
//}
//logger := New(f,"", Ldate)
//db.SetLogger(logger)
}
//db.AutoMigrate()
}
//Close clear db collection
func Close() {
if db != nil {
db.Close()
}
if redisDB != nil {
redisDB.Close()
}
}
func createDatabase() (*gorm.DB,error) {
dbType := config.GetString("db.type")
dbAddr := config.GetString("db.addr")
dbName := config.GetString("db.database")
dbUser := config.GetString("db.user")
dbPassword := config.GetString("db.password")
dbCharset := config.GetString("db.charset")
conn := ""
switch dbType {
case "mysql":
conn = fmt.Sprintf("%s:%s@(%s)/%s?charset=%s&parseTime=True&loc=Local", dbUser,dbPassword, dbAddr, dbName,dbCharset)
case "sqlite":
conn = dbAddr
case "mssql":
return nil,errors.New("TODO:suport sqlServer")
case "postgres":
hostPort := strings.Split(dbAddr, ":")
if len(hostPort) == 2{