forked from revel/revel
-
Notifications
You must be signed in to change notification settings - Fork 2
/
libs.go
86 lines (77 loc) · 2.3 KB
/
libs.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
// Copyright (c) 2012-2016 The Revel Framework Authors, All rights reserved.
// Revel Framework source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package revel
import (
"crypto/hmac"
"crypto/sha1"
"encoding/hex"
"io"
"reflect"
"strings"
)
// Sign a given string with the app-configured secret key.
// If no secret key is set, returns the empty string.
// Return the signature in base64 (URLEncoding).
func Sign(message string) string {
if len(secretKey) == 0 {
return ""
}
mac := hmac.New(sha1.New, secretKey)
if _, err := io.WriteString(mac, message); err != nil {
ERROR.Println("WriteString failed:", err)
return ""
}
return hex.EncodeToString(mac.Sum(nil))
}
// Verify returns true if the given signature is correct for the given message.
// e.g. it matches what we generate with Sign()
func Verify(message, sig string) bool {
return hmac.Equal([]byte(sig), []byte(Sign(message)))
}
// ToBool method converts/assert value into true or false. Default is true.
// When converting to boolean, the following values are considered FALSE:
// - The integer value is 0 (zero)
// - The float value 0.0 (zero)
// - The complex value 0.0 (zero)
// - For string value, please refer `revel.Atob` method
// - An array, map, slice with zero elements
// - Boolean value returned as-is
// - "nil" value
func ToBool(val interface{}) bool {
if val == nil {
return false
}
v := reflect.ValueOf(val)
switch v.Kind() {
case reflect.Bool:
return v.Bool()
case reflect.String:
return Atob(v.String())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() != 0
case reflect.Float32, reflect.Float64:
return v.Float() != 0.0
case reflect.Complex64, reflect.Complex128:
return v.Complex() != 0.0
case reflect.Array, reflect.Map, reflect.Slice:
return v.Len() != 0
}
// Return true by default
return true
}
// Atob converts string into boolean. It is in-case sensitive
// When converting to boolean, the following values are considered FALSE:
// - The "" (empty) string
// - The "false" string
// - The "f" string
// - The "off" string,
// - The string "0" & "0.0"
func Atob(v string) bool {
switch strings.TrimSpace(strings.ToLower(v)) {
case "", "false", "off", "f", "0", "0.0":
return false
}
// Return true by default
return true
}