-
Notifications
You must be signed in to change notification settings - Fork 4
/
funcs.go
842 lines (798 loc) · 18.6 KB
/
funcs.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
package funcs
import (
"bytes"
"encoding/json"
"fmt"
"html/template"
"math"
"reflect"
"strconv"
"strings"
"time"
"github.com/fefit/dateutil"
)
// OperatorNumberFn func for operate numbers
type OperatorNumberFn func(interface{}, interface{}) interface{}
// OperatorIntFn func for int types
type OperatorIntFn func(int64, int64) int64
// ResultNumberFn wrap the OperatorNumberFn
type ResultNumberFn func(args ...interface{}) interface{}
// ResultIntFn wrap the OperatorIntFn
type ResultIntFn func(args ...interface{}) int64
// JSON alias a json type
type JSON map[string]interface{}
// LoopChan used for "for" blocks
type LoopChan struct {
Chan chan int
Loop int
}
// CaptureData used for Capture
type CaptureData struct {
Variables map[string]interface{}
Data interface{}
}
func (lc *LoopChan) init() {
lc.Chan = make(chan int, 1)
lc.Loop = -1
_, _ = lc.Next()
}
// Close close the loop chan
func (lc *LoopChan) Close() (string, error) {
lc.Loop = -1
close(lc.Chan)
return "", nil
}
// Next goto the next step
func (lc *LoopChan) Next() (string, error) {
lc.Loop++
lc.Chan <- lc.Loop
return "", nil
}
// All combine
func All() template.FuncMap {
injects := Inject()
helpers := Helpers()
for key, fn := range injects {
helpers[key] = fn
}
return helpers
}
// Inject funcs
func Inject() template.FuncMap {
injects := template.FuncMap{}
injects["INJECT_PLUS"] = generateNumberFunc(func(a, b interface{}) interface{} {
if a, b, err := toIntNumbers(a, b); err == nil {
return a + b
}
if a, b, err := toFloatNumbers(a, b); err != nil {
panic(makeHaltInfo("plus(+)", err))
} else {
return a + b
}
}, true)
injects["INJECT_MINUS"] = generateNumberFunc(func(a, b interface{}) interface{} {
if a, b, err := toIntNumbers(a, b); err == nil {
return a - b
}
if a, b, err := toFloatNumbers(a, b); err != nil {
panic(makeHaltInfo("minus(-)", err))
} else {
return a - b
}
}, true)
injects["INJECT_MULTIPLE"] = generateNumberFunc(func(a, b interface{}) interface{} {
if a, b, err := toIntNumbers(a, b); err == nil {
return a * b
}
if a, b, err := toFloatNumbers(a, b); err != nil {
panic(makeHaltInfo("multiple(*)", err))
} else {
return a * b
}
}, true)
injects["INJECT_DIVIDE"] = generateNumberFunc(func(a, b interface{}) interface{} {
if a, b, err := toFloatNumbers(a, b); err != nil {
panic(makeHaltInfo("divide(/)", err))
} else {
return a / b
}
}, false)
injects["INJECT_MOD"] = generateNumberFunc(func(a, b interface{}) interface{} {
if a, b, err := toFloatNumbers(a, b); err != nil {
panic(makeHaltInfo("mod(%)", err))
} else {
return math.Mod(a, b)
}
}, false)
injects["INJECT_POWER"] = generateNumberFunc(func(a, b interface{}) interface{} {
if a, b, err := toFloatNumbers(a, b); err != nil {
panic(makeHaltInfo("power(**)", err))
} else {
return math.Pow(a, b)
}
}, false)
injects["INJECT_BITAND"] = generateIntFunc(func(a, b int64) int64 {
return a & b
})
injects["INJECT_BITOR"] = generateIntFunc(func(a, b int64) int64 {
return a | b
})
injects["INJECT_BITXOR"] = generateIntFunc(func(a, b int64) int64 {
return a ^ b
})
injects["INJECT_TO_FLOAT"] = toFloat
injects["INJECT_TO_FORS"] = toFloatOrString
injects["INJECT_MAKE_LOOP_CHAN"] = func() (*LoopChan, error) {
loopChan := &LoopChan{}
loopChan.init()
return loopChan, nil
}
injects["INJECT_INDEX"] = index
injects["INJECT_CAPTURE_SCOPE"] = capture
return injects
}
// Helpers funcs
func Helpers() template.FuncMap {
helpers := template.FuncMap{}
// output
helpers["safe"] = safe
// maths
helpers["ceil"] = ceil
helpers["floor"] = floor
helpers["min"] = generateNumberFunc(func(a, b interface{}) interface{} {
if a, b, err := toIntNumbers(a, b); err == nil {
if a < b {
return a
}
return b
}
if a, b, err := toFloatNumbers(a, b); err != nil {
panic(makeHaltInfo("min", err))
} else {
if a < b {
return a
}
return b
}
}, true)
helpers["max"] = generateNumberFunc(func(a, b interface{}) interface{} {
if a, b, err := toIntNumbers(a, b); err == nil {
if a > b {
return a
}
return b
}
if a, b, err := toFloatNumbers(a, b); err != nil {
panic(makeHaltInfo("max", err))
} else {
if a > b {
return a
}
return b
}
}, true)
// format
helpers["number_format"] = numberFormat
// strings
helpers["truncate"] = truncate
helpers["concat"] = concat
helpers["ucwords"] = strings.Title
helpers["trim"] = trim
helpers["strtolower"] = strings.ToLower
helpers["strtoupper"] = strings.ToUpper
// assert
helpers["empty"] = empty
// date
helpers["now"] = now
helpers["strtotime"] = func(target interface{}) int64 {
if timestamp, err := dateutil.StrToTime(target); err == nil {
return timestamp
} else {
panic(err)
}
}
helpers["date_format"] = func(target interface{}, format string) string {
if strTime, err := dateutil.DateFormat(target, format); err == nil {
return strTime
} else {
panic(err)
}
}
// helper
helpers["count"] = count
helpers["mrange"] = makeRange
helpers["json_encode"] = jsonEncode
helpers["json_decode"] = jsonDecode
// slice, don't add this line since go1.13
helpers["slice"] = slice
return helpers
}
func safe(html string) template.HTML {
return template.HTML(html)
}
var floatType = reflect.TypeOf(float64(0))
var intType = reflect.TypeOf(int64(0))
func toFloat(num interface{}) (float64, error) {
switch t := num.(type) {
case float64:
return t, nil
case float32:
return float64(t), nil
case int:
return float64(t), nil
case int16:
return float64(t), nil
case int32:
return float64(t), nil
case int64:
return float64(t), nil
case uint:
return float64(t), nil
case uint16:
return float64(t), nil
case uint32:
return float64(t), nil
case uint64:
return float64(t), nil
default:
v := reflect.ValueOf(num)
v = reflect.Indirect(v)
if !v.Type().ConvertibleTo(floatType) {
return 0, fmt.Errorf("cannot convert %v to float64", v.Type())
}
fv := v.Convert(floatType)
return fv.Float(), nil
}
}
func toInt(num interface{}) (int64, error) {
switch t := num.(type) {
case int64:
return t, nil
case float64:
return int64(t), nil
case int:
return int64(t), nil
case float32:
return int64(t), nil
case int16:
return int64(t), nil
case int32:
return int64(t), nil
case uint:
return int64(t), nil
case uint16:
return int64(t), nil
case uint32:
return int64(t), nil
case uint64:
return int64(t), nil
default:
v := reflect.ValueOf(num)
v = reflect.Indirect(v)
if !v.Type().ConvertibleTo(intType) {
return 0, fmt.Errorf("cannot convert %v to int", v.Type())
}
fv := v.Convert(intType)
return fv.Int(), nil
}
}
func toFloatOrString(target interface{}) (interface{}, error) {
switch t := target.(type) {
case string:
return t, nil
default:
return toFloat(target)
}
}
func trim(args ...interface{}) string {
argsNum := len(args)
if argsNum > 0 {
if target, ok := args[0].(string); ok {
chars := ` \t\n\r\0\x0B`
if argsNum == 2 {
if trims, ok := args[1].(string); ok {
chars = trims
}
}
return strings.Trim(target, chars)
}
}
return ""
}
func isInteger(target interface{}) bool {
switch target.(type) {
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
return true
case complex64, complex128:
// ignore complex
}
return false
}
func toIntNumbers(a, b interface{}) (int64, int64, error) {
var err error
if a, ok := a.(int64); ok {
if b, ok := b.(int64); ok {
return a, b, nil
}
err = fmt.Errorf("the second argument '%v' is not an int64 type", b)
} else {
err = fmt.Errorf("the first argument '%v' is not an int64 type", a)
}
return 0, 0, err
}
func toFloatNumbers(a, b interface{}) (float64, float64, error) {
var err error
if a, ok := a.(float64); ok {
if b, ok := b.(float64); ok {
return a, b, nil
}
err = fmt.Errorf("the second argument '%v' is not a float64 type", b)
} else {
err = fmt.Errorf("the first argument '%v' is not a float64 type", a)
}
return 0.0, 0.0, err
}
func makeHaltInfo(name string, err error) string {
return fmt.Sprintf("'%s' method params error:%s", name, err.Error())
}
func generateNumberFunc(fn OperatorNumberFn, allowInt bool) (res ResultNumberFn) {
var calc ResultNumberFn
calc = func(args ...interface{}) interface{} {
argsNum := len(args)
if argsNum <= 1 {
panic("wrong arguments")
}
var (
err error
result interface{}
)
f, s := args[0], args[1]
if allowInt && isInteger(f) && isInteger(s) {
// when both integer, do not convert to float
var (
first int64
second int64
)
if first, err = toInt(f); err != nil {
panic(err)
}
if second, err = toInt(s); err != nil {
panic(err)
}
result = fn(first, second)
} else {
var (
first float64
second float64
)
if first, err = toFloat(f); err != nil {
panic(err)
}
if second, err = toFloat(s); err != nil {
panic(err)
}
result = fn(first, second)
}
if argsNum > 2 {
args[1] = result
return calc(args[1:]...)
}
return result
}
return calc
}
func generateIntFunc(fn OperatorIntFn) (res ResultIntFn) {
var calc ResultIntFn
calc = func(args ...interface{}) int64 {
argsNum := len(args)
if argsNum <= 1 {
panic("wrong arguments")
}
var (
err error
first int64
second int64
)
f, s := args[0], args[1]
if first, err = toInt(f); err != nil {
panic(err)
}
if second, err = toInt(s); err != nil {
panic(err)
}
result := fn(first, second)
if argsNum > 2 {
args[1] = result
return calc(args[1:]...)
}
return result
}
return calc
}
func ceil(num float64) float64 {
return math.Ceil(num)
}
func floor(num float64) float64 {
return math.Floor(num)
}
func numberFormat(args ...interface{}) string {
decimals, dot, thousandsSep := 0, ".", ","
argsNum := len(args)
if argsNum == 0 {
panic("wrong arguments")
}
var (
err error
num float64
prefix string
suffix string
)
first := args[0]
if num, err = toFloat(first); err != nil {
panic(err)
}
if argsNum > 1 {
if dn, ok := args[1].(int); ok && dn > 0 {
decimals = dn
}
}
if argsNum > 2 {
if ds, ok := args[2].(string); ok {
dot = ds
}
}
if argsNum > 3 {
if ts, ok := args[3].(string); ok {
thousandsSep = ts
}
}
numstr := strconv.FormatFloat(num, 'f', -1, 64)
isInt := false
dotIndex := strings.Index(numstr, ".")
if dotIndex < 0 {
isInt = true
dotIndex = len(numstr)
}
prefix = numstr[:dotIndex]
pres := []rune(prefix)
total := len(pres)
splitNum := 3
modNum := total%splitNum - 1
if modNum < 0 {
modNum = 2
}
result := []rune{}
sep := []rune(thousandsSep)
for i := 0; i < total-1; i++ {
result = append(result, pres[i])
if i%3 == modNum {
result = append(result, sep...)
}
}
result = append(result, pres[total-1])
if decimals > 0 {
result = append(result, []rune(dot)...)
if !isInt {
suffix = numstr[dotIndex+1:]
sufs := []rune(suffix)
if decimals <= len(sufs) {
result = append(result, sufs[:decimals]...)
} else {
zeros := strings.Repeat("0", decimals-len(sufs))
zs := []rune(zeros)
result = append(result, sufs...)
result = append(result, zs...)
}
} else {
zeros := strings.Repeat("0", decimals)
zs := []rune(zeros)
result = append(result, zs...)
}
}
return string(result)
}
func truncate(content string, length int) string {
cont := []rune(content)
total := len(cont)
suffix := "..."
if length >= total {
return content
}
return string(cont[:length]) + suffix
}
func makeRange(s, e interface{}, args ...interface{}) []float64 {
step := 1.0
if start, err := toFloat(s); err != nil {
panic(makeHaltInfo("mrange", err))
} else {
if end, err := toFloat(e); err != nil {
panic(makeHaltInfo("mrange", err))
} else {
if len(args) == 1 {
if curStep, ok := args[0].(float64); ok && curStep != 0.0 {
step = curStep
}
}
result := []float64{
start,
}
total := math.Floor((end - start) / step)
needLast := true
if start+total*step == end {
needLast = false
}
for i := 1.0; i <= total; i++ {
result = append(result, start+step*i)
}
if needLast {
result = append(result, end)
}
return result
}
}
}
func capture(data interface{}, variables ...interface{}) CaptureData {
result := CaptureData{
Data: data,
}
vars := map[string]interface{}{}
count := len(variables)
if count > 0 && count%2 == 0 {
for i := 0; i < count; {
key := variables[i]
value := variables[i+1]
if t, ok := key.(string); ok {
vars[t] = value
}
i += 2
}
}
result.Variables = vars
return result
}
func now() int64 {
t := time.Now()
return t.Unix()
}
func stringify(target interface{}) template.HTML {
result, err := json.Marshal(target)
if err != nil {
panic(err)
}
return template.HTML(result)
}
func jsonDecode(str string, args ...interface{}) JSON {
if len(args) == 1 {
fns := template.FuncMap{
"stringify": stringify,
}
tmpl, err := template.New("").Funcs(fns).Parse(str)
if err != nil {
panic(err)
}
buf := &bytes.Buffer{}
err = tmpl.Execute(buf, args[0])
if err != nil {
panic(err)
}
str = buf.String()
}
result := JSON{}
if err := json.Unmarshal([]byte(str), &result); err != nil {
panic(err)
}
return result
}
func jsonEncode(data interface{}, args ...interface{}) string {
b, err := json.Marshal(data)
if err != nil {
panic(err)
}
return string(b[:])
}
func concat(str string, args ...interface{}) string {
var builder strings.Builder
builder.WriteString(str)
for _, cur := range args {
if cur, ok := cur.(string); ok {
builder.WriteString(cur)
}
}
return builder.String()
}
func chainObject(target interface{}, args ...interface{}) (finded bool, value interface{}, err error) {
argsNum := len(args)
if target == nil {
if argsNum > 0 {
return false, nil, fmt.Errorf("can not get field of nil")
}
return true, nil, nil
}
if argsNum == 0 {
return true, target, nil
}
firstArg := args[0]
nextArgs := args[1:]
v := reflect.ValueOf(target)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
kind := v.Kind()
isIntKey := func(kind reflect.Kind) bool {
switch kind {
case reflect.Int, reflect.Int64, reflect.Int8, reflect.Int16, reflect.Int32:
return true
}
return false
}
getIntKey := func(key interface{}) (int64, error) {
switch key := key.(type) {
case int, float64, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32:
return toInt(key)
}
return 0, fmt.Errorf("it's not an integer type")
}
if kind == reflect.Struct {
if key, ok := firstArg.(string); ok {
return chainObject(v.FieldByName(key).Interface(), nextArgs...)
}
return false, nil, fmt.Errorf("the struct field must be string type")
} else if kind == reflect.Map {
mapKeyType := v.Type().Key().Kind()
mapKeys := v.MapKeys()
if mapKeyType == reflect.String {
if key, ok := firstArg.(string); ok {
for _, mv := range mapKeys {
if name, ok := mv.Interface().(string); ok && name == key {
target = v.MapIndex(mv).Interface()
return chainObject(target, nextArgs...)
}
}
}
} else if isIntKey(mapKeyType) {
if index, err := getIntKey(firstArg); err == nil {
for _, mv := range mapKeys {
if index == mv.Int() {
target = v.MapIndex(mv).Interface()
return chainObject(target, nextArgs...)
}
}
}
}
return false, nil, fmt.Errorf("the map does not has key %v", firstArg)
} else if kind == reflect.Slice || kind == reflect.Array {
if index, err := getIntKey(firstArg); err == nil {
idx := int(index)
if idx >= 0 && idx < v.Len() {
return chainObject(v.Index(idx).Interface(), nextArgs...)
}
}
}
return false, nil, fmt.Errorf("unsupport type")
}
func index(target interface{}, args ...interface{}) interface{} {
finded, value, err := chainObject(target, args...)
if err != nil || !finded {
return nil
}
return value
}
func empty(target interface{}, args ...interface{}) bool {
finded, value, err := chainObject(target, args...)
if err != nil || !finded {
return true
}
switch v := value.(type) {
case string:
return v == "" || v == "0"
case int, int32, int8, int16, int64, uint, uint8, uint16, uint32, uint64:
return v == 0
case float64, float32:
return v == 0.0
case bool:
return !v
case nil:
return true
}
v := reflect.ValueOf(value)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
switch v.Kind() {
case reflect.Slice, reflect.Array, reflect.Map:
return v.Len() == 0
}
return false
}
func count(target interface{}, args ...interface{}) int {
if len(args) > 0 {
panic("the 'count' function can only have one param")
}
v := reflect.ValueOf(target)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
kind := v.Kind()
if kind == reflect.Map || kind == reflect.Slice || kind == reflect.Array {
return v.Len()
} else if kind == reflect.String {
vi := v.String()
return len([]rune(vi))
}
panic("the 'count' function can only used for types 'map,array,slice,string' ")
}
/**
* slice function
* since go1.13 has preinclude this function,you don't need add it to the func list.
*/
func toIntList(args ...interface{}) (result []int, err error) {
value := args[0]
if v, ok := value.(int); ok {
result = append(result, v)
} else {
var v int64
if v, err = toInt(value); err == nil {
result = append(result, int(v))
} else {
return result, err
}
}
if len(args) > 1 {
var list []int
if list, err = toIntList(args[1:]...); err == nil {
result = append(result, list...)
}
}
return result, err
}
func slice(target interface{}, args ...interface{}) interface{} {
v := reflect.ValueOf(target)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
kind := v.Kind()
switch kind {
case reflect.Array, reflect.String, reflect.Slice:
default:
panic("the 'count' function can only used for types 'array,slice,string'")
}
var (
startIndex, endIndex, lastIndex int
isSlice3 bool
err error
indexs []int
)
switch len(args) {
case 0:
startIndex, endIndex = 0, v.Len()
case 1:
if index, ok := args[0].(int); ok {
startIndex, endIndex = index, v.Len()
} else if index, err := toInt(args[0]); err == nil {
startIndex, endIndex = int(index), v.Len()
}
case 2:
if indexs, err = toIntList(args...); err == nil {
startIndex, endIndex = indexs[0], indexs[1]
} else {
panic(err)
}
case 3:
if kind == reflect.String {
panic("can't use slice3 for string type")
} else {
isSlice3 = true
if indexs, err = toIntList(args...); err == nil {
startIndex, endIndex, lastIndex = indexs[0], indexs[1], indexs[2]
} else {
panic(err)
}
}
default:
panic("too much arguments for slice function")
}
if isSlice3 {
return v.Slice3(startIndex, endIndex, lastIndex).Interface()
}
return v.Slice(startIndex, endIndex).Interface()
}