utils.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. package utils
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "fmt"
  6. "html/template"
  7. "net/http"
  8. "os"
  9. "regexp"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "golang-fave/assets"
  14. "golang-fave/consts"
  15. )
  16. func IsFileExists(filename string) bool {
  17. if _, err := os.Stat(filename); !os.IsNotExist(err) {
  18. if err == nil {
  19. return true
  20. }
  21. }
  22. return false
  23. }
  24. func IsDir(filename string) bool {
  25. if st, err := os.Stat(filename); !os.IsNotExist(err) {
  26. if err == nil {
  27. if st.Mode().IsDir() {
  28. return true
  29. }
  30. }
  31. }
  32. return false
  33. }
  34. func IsDirExists(path string) bool {
  35. if IsFileExists(path) && IsDir(path) {
  36. return true
  37. }
  38. return false
  39. }
  40. func IsNumeric(str string) bool {
  41. if _, err := strconv.Atoi(str); err == nil {
  42. return true
  43. }
  44. return false
  45. }
  46. func IsValidEmail(email string) bool {
  47. regexpe := regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`)
  48. return regexpe.MatchString(email)
  49. }
  50. func IsValidAlias(alias string) bool {
  51. regexpe := regexp.MustCompile(`^\/([a-zA-Z0-9\/\-_\.]+)\/?$`)
  52. return regexpe.MatchString(alias)
  53. }
  54. func FixPath(path string) string {
  55. newPath := strings.TrimSpace(path)
  56. if len(newPath) <= 0 {
  57. return newPath
  58. }
  59. if newPath[len(newPath)-1] == '/' || newPath[len(newPath)-1] == '\\' {
  60. newPath = newPath[0 : len(newPath)-2]
  61. }
  62. return newPath
  63. }
  64. func ExtractHostPort(host string, https bool) (string, string) {
  65. h := host
  66. p := "80"
  67. if https {
  68. p = "443"
  69. }
  70. i := strings.Index(h, ":")
  71. if i > -1 {
  72. p = h[i+1:]
  73. h = h[0:i]
  74. }
  75. return h, p
  76. }
  77. func GetAssetsUrl(filename string) string {
  78. return "/" + filename + "?v=" + consts.AssetsVersion
  79. }
  80. func GetTmplSystemData() consts.TmplSystem {
  81. return consts.TmplSystem{
  82. PathIcoFav: GetAssetsUrl(consts.AssetsSysFaveIco),
  83. PathSvgLogo: GetAssetsUrl(consts.AssetsSysLogoSvg),
  84. PathCssStyles: GetAssetsUrl(consts.AssetsSysStylesCss),
  85. PathCssCpStyles: GetAssetsUrl(consts.AssetsCpStylesCss),
  86. PathCssBootstrap: GetAssetsUrl(consts.AssetsBootstrapCss),
  87. PathJsJquery: GetAssetsUrl(consts.AssetsJqueryJs),
  88. PathJsPopper: GetAssetsUrl(consts.AssetsPopperJs),
  89. PathJsBootstrap: GetAssetsUrl(consts.AssetsBootstrapJs),
  90. PathJsCpScripts: GetAssetsUrl(consts.AssetsCpScriptsJs),
  91. }
  92. }
  93. func GetTmplError(err error) consts.TmplError {
  94. return consts.TmplError{
  95. ErrorMessage: err.Error(),
  96. }
  97. }
  98. func GetMd5(str string) string {
  99. hasher := md5.New()
  100. hasher.Write([]byte(str))
  101. return hex.EncodeToString(hasher.Sum(nil))
  102. }
  103. func GetCurrentUnixTimestamp() int64 {
  104. return int64(time.Now().Unix())
  105. }
  106. func SystemRenderTemplate(w http.ResponseWriter, c []byte, d interface{}) {
  107. tmpl, err := template.New("template").Parse(string(c))
  108. if err != nil {
  109. SystemErrorPageEngine(w, err)
  110. return
  111. }
  112. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  113. w.Header().Set("Content-Type", "text/html")
  114. tmpl.Execute(w, consts.TmplData{
  115. System: GetTmplSystemData(),
  116. Data: d,
  117. })
  118. }
  119. func SystemErrorPageEngine(w http.ResponseWriter, err error) {
  120. if tmpl, e := template.New("template").Parse(string(assets.TmplPageErrorEngine)); e == nil {
  121. w.WriteHeader(http.StatusInternalServerError)
  122. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  123. w.Header().Set("Content-Type", "text/html")
  124. tmpl.Execute(w, consts.TmplData{
  125. System: GetTmplSystemData(),
  126. Data: GetTmplError(err),
  127. })
  128. return
  129. }
  130. w.WriteHeader(http.StatusInternalServerError)
  131. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  132. w.Header().Set("Content-Type", "text/html")
  133. w.Write([]byte("<h1>Critical engine error</h1>"))
  134. w.Write([]byte("<h2>" + err.Error() + "</h2>"))
  135. }
  136. func SystemErrorPage404(w http.ResponseWriter) {
  137. tmpl, err := template.New("template").Parse(string(assets.TmplPageError404))
  138. if err != nil {
  139. SystemErrorPageEngine(w, err)
  140. return
  141. }
  142. w.WriteHeader(http.StatusNotFound)
  143. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  144. w.Header().Set("Content-Type", "text/html")
  145. tmpl.Execute(w, consts.TmplData{
  146. System: GetTmplSystemData(),
  147. Data: nil,
  148. })
  149. }
  150. func UrlToArray(url string) []string {
  151. url_buff := url
  152. if len(url_buff) >= 1 && url_buff[:1] == "/" {
  153. url_buff = url_buff[1:]
  154. }
  155. if len(url_buff) >= 1 && url_buff[len(url_buff)-1:] == "/" {
  156. url_buff = url_buff[:len(url_buff)-1]
  157. }
  158. if url_buff == "" {
  159. return []string{}
  160. } else {
  161. return strings.Split(url_buff, "/")
  162. }
  163. }
  164. func IntToStr(num int) string {
  165. return fmt.Sprintf("%d", num)
  166. }
  167. func StrToInt(str string) int {
  168. num, err := strconv.Atoi(str)
  169. if err == nil {
  170. return num
  171. }
  172. return 0
  173. }
  174. func GenerateAlias(str string) string {
  175. if str == "" {
  176. return ""
  177. }
  178. lat := []string{"EH", "I", "i", "#", "eh", "A", "B", "V", "G", "D", "E", "JO", "ZH", "Z", "I", "JJ", "K", "L", "M", "N", "O", "P", "R", "S", "T", "U", "F", "KH", "C", "CH", "SH", "SHH", "'", "Y", "", "EH", "YU", "YA", "a", "b", "v", "g", "d", "e", "jo", "zh", "z", "i", "jj", "k", "l", "m", "n", "o", "p", "r", "s", "t", "u", "f", "kh", "c", "ch", "sh", "shh", "", "y", "", "eh", "yu", "ya", "", "", "-", "-", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "[", "]", "a", "s", "d", "f", "g", "h", "j", "k", "l", ";", "'", "z", "x", "c", "v", "b", "n", "m", ",", ".", "/", "-", "-", ":", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "A", "S", "D", "F", "G", "H", "J", "K", "L", "Z", "X", "C", "V", "B", "N", "M"}
  179. cyr := []string{"Є", "І", "і", "№", "є", "А", "Б", "В", "Г", "Д", "Е", "Ё", "Ж", "З", "И", "Й", "К", "Л", "М", "Н", "О", "П", "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ъ", "Ы", "Ь", "Э", "Ю", "Я", "а", "б", "в", "г", "д", "е", "ё", "ж", "з", "и", "й", "к", "л", "м", "н", "о", "п", "р", "с", "т", "у", "ф", "х", "ц", "ч", "ш", "щ", "ъ", "ы", "ь", "э", "ю", "я", "«", "»", "—", " ", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "", "", "a", "s", "d", "f", "g", "h", "j", "k", "l", "", "", "z", "x", "c", "v", "b", "n", "m", "", "", "", "(", ")", "", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "A", "S", "D", "F", "G", "H", "J", "K", "L", "Z", "X", "C", "V", "B", "N", "M"}
  180. var alias string = ""
  181. for i := 0; i < len(str); i++ {
  182. for j := 0; j < len(cyr); j++ {
  183. if string(str[i]) == cyr[j] {
  184. alias += lat[j]
  185. }
  186. }
  187. }
  188. alias = strings.ToLower(alias)
  189. // Cut repeated chars
  190. if reg, err := regexp.Compile("[\\-]+"); err == nil {
  191. alias = strings.Trim(reg.ReplaceAllString(alias, "-"), "-")
  192. }
  193. return "/" + strings.Trim(alias, " ") + "/"
  194. }
  195. func UnixTimestampToMySqlDateTime(value int64) string {
  196. return time.Unix(value, 0).Format("2006-01-02 15:04:05")
  197. }