-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
194 lines (164 loc) · 4.48 KB
/
utils.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
package utils
import (
"fmt"
"net/http"
"net/url"
"os"
"reflect"
"regexp"
"runtime"
"runtime/debug"
"time"
"github.com/jinzhu/gorm"
"github.com/qor/qor"
"strings"
)
// Humanize separates string based on capitalizd letters
// e.g. "OrderItem" -> "Order Item"
func HumanizeString(str string) string {
var human []rune
for i, l := range str {
if i > 0 && isUppercase(byte(l)) {
if i > 0 && !isUppercase(str[i-1]) || i+1 < len(str) && !isUppercase(str[i+1]) {
human = append(human, rune(' '))
}
}
human = append(human, l)
}
return strings.Title(string(human))
}
func isUppercase(char byte) bool {
return 'A' <= char && char <= 'Z'
}
// ToParamString replaces spaces and separates words (by uppercase letters) with
// underscores in a string, also downcase it
// e.g. ToParamString -> to_param_string, To ParamString -> to_param_string
var upcaseRegexp = regexp.MustCompile("[A-Z]{3,}[a-z]")
func ToParamString(str string) string {
if len(str) <= 1 {
return strings.ToLower(str)
}
str = strings.Replace(str, " ", "_", -1)
str = upcaseRegexp.ReplaceAllStringFunc(str, func(s string) string {
return s[0:1] + strings.ToLower(s[1:len(s)-2]) + s[len(s)-2:]
})
result := []rune{rune(str[0])}
for _, l := range str[1:] {
if rune('A') <= l && l <= rune('Z') {
if lr := len(result); lr == 0 || (result[lr-1] != '_' && !(rune('A') <= result[lr-1] && result[lr-1] <= rune('Z'))) {
result = append(result, rune('_'), l)
continue
}
}
result = append(result, l)
}
return strings.ToLower(string(result))
}
// PatchURL updates the query part of the current request url. You can
// access it in template by `patch_url`.
// patch_url "google.com" "key" "value"
func PatchURL(originalURL string, params ...interface{}) (patchedURL string, err error) {
url, err := url.Parse(originalURL)
if err != nil {
return
}
query := url.Query()
for i := 0; i < len(params)/2; i++ {
// Check if params is key&value pair
key := fmt.Sprintf("%v", params[i*2])
value := fmt.Sprintf("%v", params[i*2+1])
if value == "" {
query.Del(key)
} else {
query.Set(key, value)
}
}
url.RawQuery = query.Encode()
patchedURL = url.String()
return
}
func GetLocale(context *qor.Context) string {
if locale := context.Request.Header.Get("Locale"); locale != "" {
return locale
}
if locale := context.Request.URL.Query().Get("locale"); locale != "" {
if context.Writer != nil {
context.Request.Header.Set("Locale", locale)
c := http.Cookie{Name: "locale", Value: locale, Expires: time.Now().AddDate(1, 0, 0), Path: "/"}
http.SetCookie(context.Writer, &c)
}
return locale
}
if locale, err := context.Request.Cookie("locale"); err == nil {
return locale.Value
}
return ""
}
func Stringify(object interface{}) string {
if obj, ok := object.(interface {
Stringify() string
}); ok {
return obj.Stringify()
}
scope := gorm.Scope{Value: object}
for _, column := range []string{"Name", "Title"} {
if field, ok := scope.FieldByName(column); ok {
return fmt.Sprintf("%v", field.Field.Interface())
}
}
if scope.PrimaryField() != nil {
if scope.PrimaryKeyZero() {
return ""
} else {
return fmt.Sprintf("%v#%v", scope.GetModelStruct().ModelType.Name(), scope.PrimaryKeyValue())
}
} else {
return fmt.Sprint(reflect.Indirect(reflect.ValueOf(object)).Interface())
}
}
func ModelType(value interface{}) reflect.Type {
reflectValue := reflect.Indirect(reflect.ValueOf(value))
if reflectValue.Kind() == reflect.Slice {
typ := reflectValue.Type().Elem()
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
return typ
}
return reflectValue.Type()
}
func ParseTagOption(str string) map[string]string {
tags := strings.Split(str, ";")
setting := map[string]string{}
for _, value := range tags {
v := strings.Split(value, ":")
k := strings.TrimSpace(strings.ToUpper(v[0]))
if len(v) == 2 {
setting[k] = v[1]
} else {
setting[k] = k
}
}
return setting
}
func filenameWithLineNum() string {
var total = 10
var results []string
for i := 2; i < 15; i++ {
if _, file, line, ok := runtime.Caller(i); ok {
total--
results = append(results[:0],
append(
[]string{fmt.Sprintf("%v:%v", strings.TrimPrefix(file, os.Getenv("GOPATH")+"src/"), line)},
results[0:len(results)]...)...)
if total == 0 {
return strings.Join(results, "\n")
}
}
}
return ""
}
func ExitWithMsg(msg interface{}, value ...interface{}) {
fmt.Printf("\n"+filenameWithLineNum()+"\n%v\n", append([]interface{}{msg}, value...)...)
debug.PrintStack()
}