-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcontext.go
1385 lines (1248 loc) · 33 KB
/
context.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
// Copyright 2018 The axx Authors. All rights reserved.
package bast
import (
"bufio"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"io/ioutil"
"math"
"net"
"net/http"
"net/url"
"path/filepath"
"reflect"
"strconv"
"strings"
"github.com/axfor/bast/conf"
"github.com/axfor/bast/guid"
"github.com/axfor/bast/lang"
"github.com/axfor/bast/logs"
"github.com/axfor/bast/session/engine"
"github.com/axfor/bast/validate"
"github.com/julienschmidt/httprouter"
"gopkg.in/yaml.v2"
)
//const code
const (
SerError = 0 // error code
SerOK = 1 // ok code
SerDBError = -10000 // db error code
SerNoDataError = -20000 // no data error code
SerSignOutError = -30000 // user sign out error code
SerUserNotExistError = -40000 // user not exist code
SerInvalidParamError = -50000 // invalid param code
SerInvalidUserAuthorize = -60000 // invalid user authorize code
SerExist = -70000 // exist code
SerNotExist = -80000 // not exist code
SerTry = -99999 // please try code
SerMustFailed = -111111 // must failed code
SerFailed = -222222 // failed code
SerAuthorizationFailed = -888888 // authorization failed code
KindAcceptJSON = 0 // json
KindAcceptXML = 1 // xml
KindAcceptYAML = 2 // yaml
)
//default validator
var valid = validate.Validator{}
//Context is app Context
type Context struct {
//In A Request represents an HTTP request received by a server
// or to be sent by a client.
In *http.Request
//Accept
Accept string
//Kind Accept
KindAccept int
//Out A ResponseWriter interface is used by an HTTP handler to
// construct an HTTP response.
Out http.ResponseWriter
//Params httprouter Params,/:name/:age
Params httprouter.Params
//isParseForm Parse tag
isParseForm bool
//NeedAuthorization is need authorization
NeedAuthorization bool
//IsAuthorization is authorization finish?
IsAuthorization bool
//Session is session
Session engine.Store
//Router
Router *Pattern
}
//Message is response message
type Message struct {
XMLName xml.Name `xml:"msg" json:"-" yaml:"-"`
Code int `json:"code" xml:"code" yaml:"code"`
Msg string `json:"msg" xml:"msg" yaml:"msg"`
}
//MessageDetail is response detail message
type MessageDetail struct {
XMLName xml.Name `xml:"msg" json:"-" yaml:"-"`
Code int `json:"code" xml:"code" yaml:"code"`
Msg string `json:"msg" xml:"msg" yaml:"msg"`
Detail string `json:"detail" xml:"detail" yaml:"detail"`
}
//Datum is response data
type Datum struct {
Message `yaml:",inline"`
XMLName xml.Name `xml:"data" json:"-" yaml:"-"`
Data interface{} `json:"data" xml:"data>data" yaml:"data"`
}
//Pagination is Pagination data
type Pagination struct {
Message `yaml:",inline"`
XMLName xml.Name `xml:"page" json:"-" yaml:"-"`
Data interface{} `json:"data" xml:"data>data" yaml:"data"`
Page int `json:"page" xml:"page" yaml:"page"`
Total int `json:"total" xml:"total" yaml:"total"`
}
//InvalidPagination is invalid Pagination data
type InvalidPagination struct {
Pagination `yaml:",inline"`
XMLName xml.Name `xml:"page" json:"-" yaml:"-"`
Invalid bool `json:"invalid" xml:"invalid" yaml:"invalid"`
Fix bool `json:"fix" xml:"fix" yaml:"fix"`
}
/**********data start**********/
//Data output Data data to client
//v data
func (c *Context) Data(v interface{}) {
c.DataWithCodeMsg(v, SerOK, "")
}
//DataWithCode output Data data to client
//v data
//code is message code
func (c *Context) DataWithCode(v interface{}, code int) {
c.DataWithCodeMsg(v, code, "")
}
//DataWithMsg output data to client
//v data
//msg is string message
func (c *Context) DataWithMsg(v interface{}, msg string) {
c.DataWithCodeMsg(v, SerOK, msg)
}
//DataWithCodeMsg output data to client
//v data
//code is message code
//msg is string message
func (c *Context) DataWithCodeMsg(v interface{}, code int, msg string) {
c.DataResult(c.ObjWithCodeMsg(v, code, msg))
}
//DataResult output Data data to client
func (c *Context) DataResult(v interface{}) {
switch c.KindAccept {
case KindAcceptJSON:
c.JSONResult(v)
break
case KindAcceptXML:
c.XMLResult(v)
break
case KindAcceptYAML:
c.YAMLResult(v)
break
}
}
/**********data end**********/
/**********page start**********/
//Page output pagination data data to client
//v data
//page is page
//total is total row count
func (c *Context) Page(v interface{}, page, total int) {
c.PageWithCodeMsg(v, page, total, SerOK, "")
}
//PageWithCode output pagination data to client
//v data
//page is page
//total is total row count
//code is message code
func (c *Context) PageWithCode(v interface{}, page, total, code int) {
c.PageWithCodeMsg(v, page, total, code, "")
}
//PageWithCodeMsg output pagination data to client
//v data
//page is page
//total is total row count
//code is message code
//msg is string message
func (c *Context) PageWithCodeMsg(v interface{}, page, total, code int, msg string) {
c.DataResult(c.ObjWithPageCodeMsg(v, page, total, code, msg))
}
/**********page end**********/
/**********json start**********/
//JSON output JSON data to client
//v data
func (c *Context) JSON(v interface{}) {
c.JSONWithCodeMsg(v, SerOK, "")
}
//JSONWithCode output JSON data to client
//v data
//code is message code
func (c *Context) JSONWithCode(v interface{}, code int) {
c.JSONWithCodeMsg(v, code, "")
}
//JSONWithMsg output JSON data to client
//v data
//msg is string message
func (c *Context) JSONWithMsg(v interface{}, msg string) {
c.JSONWithCodeMsg(v, SerOK, msg)
}
//JSONWithCodeMsg output JSON data to client
//v data
//code is message code
//msg is string message
func (c *Context) JSONWithCodeMsg(v interface{}, code int, msg string) {
c.JSONResult(c.ObjWithCodeMsg(v, code, msg))
}
//JSONWithPage output pagination JSON data to client
//v data
//page is page
//total is total row count
func (c *Context) JSONWithPage(v interface{}, page, total int) {
c.JSONWithPageCodeMsg(v, page, total, SerOK, "")
}
//JSONWithPageCode output pagination JSON data to client
//v data
//page is page
//total is total row count
//code is message code
func (c *Context) JSONWithPageCode(v interface{}, page, total, code int) {
c.JSONWithPageCodeMsg(v, page, total, code, "")
}
//JSONWithPageCodeMsg output pagination JSON data to client
//v data
//page is page
//total is total row count
//code is message code
//msg is string message
func (c *Context) JSONWithPageCodeMsg(v interface{}, page, total, code int, msg string) {
c.JSONResult(c.ObjWithPageCodeMsg(v, page, total, code, msg))
}
//JSONResult output json data to client
func (c *Context) JSONResult(v interface{}) {
data, err := json.Marshal(v)
if err != nil {
logs.Errors("JSONResult error", err)
c.StatusCode(http.StatusInternalServerError)
return
}
c.Out.Header().Set("Content-Type", "application/json")
c.Out.Write(data)
data = nil
}
/**********json end**********/
/**********xml start**********/
//XML output XML data to client
//v data
func (c *Context) XML(v interface{}) {
c.XMLWithCodeMsg(v, SerOK, "")
}
//XMLWithCode output XML data to client
//v data
//code is message code
func (c *Context) XMLWithCode(v interface{}, code int) {
c.XMLWithCodeMsg(v, code, "")
}
//XMLWithMsg output XML data to client
//v data
//msg is string message
func (c *Context) XMLWithMsg(v interface{}, msg string) {
c.XMLWithCodeMsg(v, SerOK, msg)
}
//XMLWithCodeMsg output XML data to client
//v data
//code is message code
//msg is string message
func (c *Context) XMLWithCodeMsg(v interface{}, code int, msg string) {
c.XMLResult(c.ObjWithCodeMsg(v, code, msg))
}
//XMLWithPage output pagination XML data to client
//v data
//page is page
//total is total row count
func (c *Context) XMLWithPage(v interface{}, page, total int) {
c.XMLWithPageCodeMsg(v, page, total, SerOK, "")
}
//XMLWithPageCode output pagination XML data to client
//v data
//page is page
//total is total row count
//code is message code
func (c *Context) XMLWithPageCode(v interface{}, page, total, code int) {
c.XMLWithPageCodeMsg(v, page, total, code, "")
}
//XMLWithPageCodeMsg output pagination XML data to client
//v data
//page is page
//total is total row count
//code is message code
//msg is string message
func (c *Context) XMLWithPageCodeMsg(v interface{}, page, total, code int, msg string) {
c.XMLResult(c.ObjWithPageCodeMsg(v, page, total, code, msg))
}
//XMLResult output xml data to client
func (c *Context) XMLResult(v interface{}) {
data, err := xml.Marshal(v)
if err != nil {
logs.Errors("XMLResult error", err)
c.StatusCode(http.StatusInternalServerError)
return
}
c.Out.Header().Set("Content-Type", "application/xml")
c.Out.Write(data)
data = nil
}
/**********xml end**********/
/**********yaml start**********/
//YAML output YAML data to client
//v data
func (c *Context) YAML(v interface{}) {
c.YAMLWithCodeMsg(v, SerOK, "")
}
//YAMLWithCode output YAML data to client
//v data
//code is message code
func (c *Context) YAMLWithCode(v interface{}, code int) {
c.YAMLWithCodeMsg(v, code, "")
}
//YAMLWithMsg output YAML data to client
//v data
//msg is string message
func (c *Context) YAMLWithMsg(v interface{}, msg string) {
c.YAMLWithCodeMsg(v, SerOK, msg)
}
//YAMLWithCodeMsg output YAML data to client
//v data
//code is message code
//msg is string message
func (c *Context) YAMLWithCodeMsg(v interface{}, code int, msg string) {
c.YAMLResult(c.ObjWithCodeMsg(v, code, msg))
}
//YAMLWithPage output pagination YAML data to client
//v data
//page is page
//total is total row count
func (c *Context) YAMLWithPage(v interface{}, page, total int) {
c.YAMLWithPageCodeMsg(v, page, total, SerOK, "")
}
//YAMLWithPageCode output pagination YAML data to client
//v data
//page is page
//total is total row count
//code is message code
func (c *Context) YAMLWithPageCode(v interface{}, page, total, code int) {
c.YAMLWithPageCodeMsg(v, page, total, code, "")
}
//YAMLWithPageCodeMsg output pagination YAML data to client
//v data
//page is page
//total is total row count
//code is message code
//msg is string message
func (c *Context) YAMLWithPageCodeMsg(v interface{}, page, total, code int, msg string) {
c.YAMLResult(c.ObjWithPageCodeMsg(v, page, total, code, msg))
}
//YAMLResult output yaml data to client
func (c *Context) YAMLResult(v interface{}) {
data, err := yaml.Marshal(v)
if err != nil {
logs.Errors("YAMLResult error", err)
c.StatusCode(http.StatusInternalServerError)
return
}
c.Out.Header().Set("Content-Type", "application/x+yaml")
c.Out.Write(data)
data = nil
}
/**********yaml end**********/
//ObjWithCodeMsg return obj data
//v data
//code is message code
//msg is string message
func (c *Context) ObjWithCodeMsg(v interface{}, code int, msg string) interface{} {
if !app.wrap {
return v
}
if isDatumType(v) || isPaginationType(v) || isInvalidPaginationType(v) || isMessageType(v) || isMessageDetailType(v) {
return v
}
d := &Datum{}
d.Code = code
d.Msg = msg
d.Data = v
return d
}
func isDatumType(v interface{}) bool {
_, ok := v.(*Datum)
return ok
}
func isPaginationType(v interface{}) bool {
_, ok := v.(*Pagination)
return ok
}
func isInvalidPaginationType(v interface{}) bool {
_, ok := v.(*InvalidPagination)
return ok
}
func isMessageType(v interface{}) bool {
_, ok := v.(*Message)
return ok
}
func isMessageDetailType(v interface{}) bool {
_, ok := v.(*MessageDetail)
return ok
}
//ObjWithPageCodeMsg return pagination obj data
//v data
//page is page
//total is total row count
//code is message code
//msg is string message
func (c *Context) ObjWithPageCodeMsg(v interface{}, page, total, code int, msg string) interface{} {
if !app.wrap {
return v
}
d := &InvalidPagination{}
_, _total, pageRow := c.GetPage()
if _total == 0 {
last := int(math.Ceil(float64(total) / float64(pageRow)))
if page >= last {
page = last - 1
d.Fix = true
}
}
page++
if v != nil {
switch reflect.TypeOf(v).Kind() {
case reflect.Array:
case reflect.Map:
case reflect.Slice:
s := reflect.ValueOf(v)
if s.Len() == 0 {
d.Invalid = true
}
break
}
} else {
d.Invalid = true
}
d.Data = v
d.Page = page
d.Total = total
d.Code = code
d.Msg = msg
if d.Invalid || d.Fix {
return d
}
return d.Pagination
}
// Pusher is the interface implemented by ResponseWriters that support
// HTTP/2 server push. For more background, see
// https://tools.ietf.org/html/rfc7540#section-8.2.
func (c *Context) Pusher() http.Pusher {
if per, ok := c.Out.(http.Pusher); ok {
return per
}
return nil
}
// Flush sends any buffered data to the client
func (c *Context) Flush() {
if puser, ok := c.Out.(http.Flusher); ok {
puser.Flush()
}
}
// Hijack implements the http.Hijacker interface.
func (c *Context) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if hijer, ok := c.Out.(http.Hijacker); ok {
return hijer.Hijack()
}
return nil, nil, errors.New("not support http hijacker")
}
//Success output success result to client
// msg is success message
func (c *Context) Success(msg string) {
v := &Message{}
v.Code = SerOK
v.Msg = msg
c.Data(v)
}
//Successf output success result and format to client
func (c *Context) Successf(format string, a ...interface{}) {
if a != nil && len(a) > 0 {
format = fmt.Sprintf(format, a...)
}
v := &Message{}
v.Code = SerOK
v.Msg = format
c.Data(v)
}
//Failed output failed result to client
//param:
// msg is fail message
// err error
func (c *Context) Failed(msg string, err ...error) {
c.FailResult(msg, SerError, err...)
}
//Faileds output failed detail result to client
//param:
// msg is fail message
// detail is detail message
func (c *Context) Faileds(msg string, detail string) {
v := &MessageDetail{}
v.Code = SerError
v.Msg = msg
v.Detail = detail
c.DataWithCode(v, SerError)
}
//Failedf output failed result and format to client
func (c *Context) Failedf(format string, a ...interface{}) {
var err error
if a != nil {
lg := len(a)
if lg > 0 {
if a[lg-1] != nil {
err, _ = a[lg-1].(error)
}
if err != nil {
a = a[0 : lg-1]
}
if len(a) > 0 {
format = fmt.Sprintf(format, a...)
}
}
}
c.FailResult(format, SerError, err)
}
//Result output result to client
//param:
// msg is fail message
// detail is detail message
func (c *Context) Result(msg string, detail ...string) {
v := &MessageDetail{}
v.Code = SerOK
v.Msg = msg
if detail != nil {
for _, s := range detail {
if v.Detail != "" {
v.Detail += ","
}
v.Detail += s
}
}
c.DataWithCode(v, SerError)
v = nil
}
//FailResult output fail result to client
//param:
// msg failed message
// errCode ailed message code
// err error
func (c *Context) FailResult(msg string, errCode int, err ...error) {
v := &Message{}
if errCode == 0 {
errCode = SerError
}
v.Code = errCode
v.Msg = msg
if err != nil && err[0] != nil {
v.Msg += ", [" + err[0].Error() + "]"
}
c.DataWithCode(v, errCode)
}
//SignOut output user signout to client
//param:
// msg message
func (c *Context) SignOut(msg string) {
c.FailResult(msg, SerSignOutError)
}
//NoData output no data result to client
//param:
// err message
func (c *Context) NoData(msg string) {
c.FailResult(msg, SerNoDataError)
}
//Say output raw bytes to client
//param:
// data raw bytes
func (c *Context) Say(data []byte) {
c.Out.Write(data)
}
//Says output string to client
//param:
// str string
func (c *Context) Says(str string) {
c.Out.Write([]byte(str))
}
//SendFile send file to client
//param:
// fileName is file name
// rawFileName is raw file name
func (c *Context) SendFile(fileName string, rawFileName ...string) {
dir := filepath.Dir(fileName)
fileName = filepath.Base(fileName)
url := c.BaseURL("f/" + fileName)
fileName = "/f/" + fileName
fs := http.StripPrefix("/f/", http.FileServer(http.Dir(dir)))
r, _ := http.NewRequest("GET", url, nil)
raw := fileName
if rawFileName != nil {
raw = rawFileName[0]
c.Out.Header().Set("Content-Disposition", "attachment; filename="+raw)
}
fs.ServeHTTP(c.Out, r)
r = nil
fs = nil
}
//JSON2String JSON to string
//param:
// obj is object
func (c *Context) JSON2String(obj interface{}) (string, error) {
data, err := json.Marshal(obj)
if err != nil {
return "", nil
}
return string(data), err
}
//String2JSON string to JSON
//param:
// str json string
// obj is object
func (c *Context) String2JSON(str string, obj interface{}) error {
return c.JSONDecode(strings.NewReader(str), obj)
}
//Verify verify current request
//param:
//rules is validate rule such as:
// key1@required|int|min:1
// key2/key2_translator@required|string|min:1
// key3@sometimes|required|data
func (c *Context) Verify(rules ...string) error {
return c.Validate(rules...)
}
//Validate verify current request
//param:
//rules is validate rule such as:
// key1@required|int|min:1
// key2/key2_translator@required|string|min:1
// key3@sometimes|required|data
func (c *Context) Validate(rules ...string) error {
c.In.ParseForm()
return valid.Request(c.In.Form, rules...)
}
//StatusCode set current request statusCode
//param:
// statusCode HTTP status code. such as: 200x,300x and so on
func (c *Context) StatusCode(statusCode int) {
c.Out.WriteHeader(statusCode)
c.Out.Write([]byte(http.StatusText(statusCode)))
}
//RawString getter raw string value from current request(request body)
func (c *Context) RawString() string {
body, err := ioutil.ReadAll(c.In.Body)
if err != nil {
return ""
}
return string(body)
}
//GetString gets a string value from the current request based on the key
//param:
// key is key name
func (c *Context) GetString(key string) string {
d := c.GetStrings(key)
if len(d) > 0 {
return d[0]
}
return ""
}
//GetStringValue gets a string value from the current request based on the key
//param:
// key is key name
// def is default value
func (c *Context) GetStringValue(key string, def string) string {
d := c.GetString(key)
if d != "" {
return d
}
return def
}
//GetTrimString Use the key to get a non-space string value from the current request
//param:
// key is key name
func (c *Context) GetTrimString(key string) string {
return strings.TrimSpace(c.GetString(key))
}
//GetStringSlice Use the key to get all string value from the current request
//param:
// key is key name
// sep spilt char
func (c *Context) GetStringSlice(key, sep string) []string {
s := c.GetTrimString(key)
if len(s) > 0 {
ss := strings.Split(s, sep)
if len(ss) > 0 {
return ss
}
}
return nil
}
//GetIntSlice Use the key to get all int value from the current request
//param:
// key is key name
// sep spilt char
func (c *Context) GetIntSlice(key, sep string) []int64 {
s := c.GetTrimString(key)
if len(s) > 0 {
ss := strings.Split(s, sep)
lg := len(ss)
si := make([]int64, lg, lg)
for i := 0; i < lg; i++ {
si[i], _ = strconv.ParseInt(ss[i], 10, 64)
}
if len(si) > 0 {
return si
}
}
return nil
}
//GetIntSliceAndRemovePrefix Use the key to get all int value from the current request and remove prefix of each
//param:
// key is key name
// sep spilt char
// prefix remove prefix string
func (c *Context) GetIntSliceAndRemovePrefix(key, sep, prefix string) ([]int64, bool) {
s := c.GetTrimString(key)
has := false
if len(s) > 0 {
if prefix != "" {
has = strings.HasPrefix(s, prefix)
s = strings.TrimPrefix(s, prefix)
}
ss := strings.Split(s, sep)
lg := len(ss)
si := make([]int64, 0, lg)
for i := 0; i < lg; i++ {
n, err := strconv.ParseInt(ss[i], 10, 64)
if err == nil {
si = append(si, n)
}
}
if len(si) > 0 {
return si, has
}
}
return nil, false
}
//GetParam Use the key to get all int value from the current request url
//note:xx/:name/:name2
//param:
// key key name
func (c *Context) GetParam(key string) string {
return c.Params.ByName(key)
}
//GetLeftLikeString get a sql(left like 'xx%') string value from the current request based on the key
//param:
// key is key name
func (c *Context) GetLeftLikeString(key string) string {
d := c.GetStrings(key)
if len(d) > 0 {
r := d[0]
if r != "" {
return r + "%"
}
}
return ""
}
//GetRightLikeString get a sql(right like '%xx') string value from the current request based on the key
//param:
// key is key name
func (c *Context) GetRightLikeString(key string) string {
d := c.GetStrings(key)
if len(d) > 0 {
r := d[0]
if r != "" {
return "%" + r
}
}
return ""
}
//GetLikeString get a sql(like '%xx%') string value from the current request based on the key
//param:
// key is key name
func (c *Context) GetLikeString(key string) string {
d := c.GetStrings(key)
if len(d) > 0 {
r := d[0]
if r != "" {
return "%" + r + "%"
}
}
return ""
}
//GetBool get a bool value from the current request based on the key
//param:
// key is key name
func (c *Context) GetBool(key string) bool {
d := c.GetStrings(key)
if len(d) > 0 {
ok, err := strconv.ParseBool(d[0])
if err == nil {
return ok
}
}
return false
}
//GetBoolValue get a bool value from the current request based on the key
//param:
// key is key name
// def is default value
func (c *Context) GetBoolValue(key string, def bool) bool {
d := c.GetStrings(key)
if len(d) > 0 {
ok, err := strconv.ParseBool(d[0])
if err == nil {
return ok
}
}
return def
}
//GetStrings gets strings from the current request based on the key
//param:
// key is key name
func (c *Context) GetStrings(key string) []string {
c.ParseForm()
return c.In.Form[key]
}
//GetInt gets a int value from the current request based on the key
//param:
// key is key name
// def default value
func (c *Context) GetInt(key string) (int, error) {
return strconv.Atoi(c.GetString(key))
}
//GetIntValue gets a int value from the current request based on the key(errors not included)
//param:
// key is key name
// def default value
func (c *Context) GetIntValue(key string, def int) int {
d := c.GetString(key)
v, err := strconv.Atoi(d)
if err != nil {
v = def
}
return v
}
//GetInt64 gets a int64 value from the current request url based on the key
//param:
// key is key name
// def default value
func (c *Context) GetInt64(key string) (int64, error) {
return strconv.ParseInt(c.GetString(key), 10, 64)
}
//GetInt64Value gets a int64 value from the current request based on the key(errors not included)
//param:
// key is key name
// def default value
func (c *Context) GetInt64Value(key string, def int64) int64 {
d := c.GetString(key)
v, err := strconv.ParseInt(d, 10, 64)
if err != nil {
v = def
}
return v
}
//GetFloat gets a float value from the current request uri based on the key
//param:
// key is key name
// def default value
func (c *Context) GetFloat(key string) (float64, error) {
return strconv.ParseFloat(c.GetString(key), 64)
}
//GetFloatValue gets a float value from the current request based on the key(errors not included)
//param:
// key is key name
// def default value
func (c *Context) GetFloatValue(key string, def float64) float64 {
d := c.GetString(key)
v, err := strconv.ParseFloat(d, 64)
if err != nil {
v = def
}
return v
}
//GetLang return
func (c *Context) GetLang() string {
return c.GetStringValue("lang", conf.Lang())
}
//HasParam has a param from the current request based on the key(May not have a value)
//param:
// key is key name
func (c *Context) HasParam(key string) bool {
c.ParseForm()
_, ok := c.In.Form[key]
return ok
}
//Form gets all form params from the current(uri not included)
func (c *Context) Form() url.Values {
c.ParseForm()
return c.In.Form
}
//PostForm gets all form params from the current(uri and form)
func (c *Context) PostForm() url.Values {
c.ParseForm()
return c.In.PostForm
}