helpers.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. package xweb
  2. import (
  3. "bytes"
  4. "net/http"
  5. "net/url"
  6. "os"
  7. "path"
  8. "reflect"
  9. "regexp"
  10. "strings"
  11. "sync"
  12. "time"
  13. )
  14. // the func is the same as condition ? true : false
  15. func Ternary(express bool, trueVal interface{}, falseVal interface{}) interface{} {
  16. if express {
  17. return trueVal
  18. }
  19. return falseVal
  20. }
  21. // internal utility methods
  22. func webTime(t time.Time) string {
  23. ftime := t.Format(time.RFC1123)
  24. if strings.HasSuffix(ftime, "UTC") {
  25. ftime = ftime[0:len(ftime)-3] + "GMT"
  26. }
  27. return ftime
  28. }
  29. func JoinPath(paths ...string) string {
  30. if len(paths) < 1 {
  31. return ""
  32. }
  33. res := ""
  34. for _, p := range paths {
  35. res = path.Join(res, p)
  36. }
  37. return res
  38. }
  39. func PageSize(total, limit int) int {
  40. if total <= 0 {
  41. return 1
  42. } else {
  43. x := total % limit
  44. if x > 0 {
  45. return total/limit + 1
  46. } else {
  47. return total / limit
  48. }
  49. }
  50. }
  51. func SimpleParse(data string) map[string]string {
  52. configs := make(map[string]string)
  53. lines := strings.Split(string(data), "\n")
  54. for _, line := range lines {
  55. line = strings.TrimRight(line, "\r")
  56. vs := strings.Split(line, "=")
  57. if len(vs) == 2 {
  58. configs[strings.TrimSpace(vs[0])] = strings.TrimSpace(vs[1])
  59. }
  60. }
  61. return configs
  62. }
  63. func dirExists(dir string) bool {
  64. d, e := os.Stat(dir)
  65. switch {
  66. case e != nil:
  67. return false
  68. case !d.IsDir():
  69. return false
  70. }
  71. return true
  72. }
  73. func fileExists(dir string) bool {
  74. info, err := os.Stat(dir)
  75. if err != nil {
  76. return false
  77. }
  78. return !info.IsDir()
  79. }
  80. // Urlencode is a helper method that converts a map into URL-encoded form data.
  81. // It is a useful when constructing HTTP POST requests.
  82. func Urlencode(data map[string]string) string {
  83. var buf bytes.Buffer
  84. for k, v := range data {
  85. buf.WriteString(url.QueryEscape(k))
  86. buf.WriteByte('=')
  87. buf.WriteString(url.QueryEscape(v))
  88. buf.WriteByte('&')
  89. }
  90. s := buf.String()
  91. return s[0 : len(s)-1]
  92. }
  93. func UnTitle(s string) string {
  94. if len(s) < 2 {
  95. return strings.ToLower(s)
  96. }
  97. return strings.ToLower(string(s[0])) + s[1:]
  98. }
  99. var slugRegex = regexp.MustCompile(`(?i:[^a-z0-9\-_])`)
  100. // Slug is a helper function that returns the URL slug for string s.
  101. // It's used to return clean, URL-friendly strings that can be
  102. // used in routing.
  103. func Slug(s string, sep string) string {
  104. if s == "" {
  105. return ""
  106. }
  107. slug := slugRegex.ReplaceAllString(s, sep)
  108. if slug == "" {
  109. return ""
  110. }
  111. quoted := regexp.QuoteMeta(sep)
  112. sepRegex := regexp.MustCompile("(" + quoted + "){2,}")
  113. slug = sepRegex.ReplaceAllString(slug, sep)
  114. sepEnds := regexp.MustCompile("^" + quoted + "|" + quoted + "$")
  115. slug = sepEnds.ReplaceAllString(slug, "")
  116. return strings.ToLower(slug)
  117. }
  118. // NewCookie is a helper method that returns a new http.Cookie object.
  119. // Duration is specified in seconds. If the duration is zero, the cookie is permanent.
  120. // This can be used in conjunction with ctx.SetCookie.
  121. func NewCookie(name string, value string, age int64) *http.Cookie {
  122. var utctime time.Time
  123. if age == 0 {
  124. // 2^31 - 1 seconds (roughly 2038)
  125. utctime = time.Unix(2147483647, 0)
  126. } else {
  127. utctime = time.Unix(time.Now().Unix()+age, 0)
  128. }
  129. return &http.Cookie{Name: name, Value: value, Expires: utctime}
  130. }
  131. func removeStick(uri string) string {
  132. uri = strings.TrimRight(uri, "/")
  133. if uri == "" {
  134. uri = "/"
  135. }
  136. return uri
  137. }
  138. var (
  139. fieldCache = make(map[reflect.Type]map[string]int)
  140. fieldCacheMutex sync.RWMutex
  141. )
  142. // this method cache fields' index to field name
  143. func fieldByName(v reflect.Value, name string) reflect.Value {
  144. t := v.Type()
  145. fieldCacheMutex.RLock()
  146. cache, ok := fieldCache[t]
  147. fieldCacheMutex.RUnlock()
  148. if !ok {
  149. cache = make(map[string]int)
  150. for i := 0; i < v.NumField(); i++ {
  151. cache[t.Field(i).Name] = i
  152. }
  153. fieldCacheMutex.Lock()
  154. fieldCache[t] = cache
  155. fieldCacheMutex.Unlock()
  156. }
  157. if i, ok := cache[name]; ok {
  158. return v.Field(i)
  159. }
  160. return reflect.Zero(t)
  161. }