utils.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. regexpeSlash := regexp.MustCompile(`[\/]{2,}`)
  52. regexpeChars := regexp.MustCompile(`^\/([a-zA-Z0-9\/\-_\.]+)\/?$`)
  53. return (!regexpeSlash.MatchString(alias) && regexpeChars.MatchString(alias)) || alias == "/"
  54. }
  55. func FixPath(path string) string {
  56. newPath := strings.TrimSpace(path)
  57. if len(newPath) <= 0 {
  58. return newPath
  59. }
  60. if newPath[len(newPath)-1] == '/' || newPath[len(newPath)-1] == '\\' {
  61. newPath = newPath[0 : len(newPath)-2]
  62. }
  63. return newPath
  64. }
  65. func ExtractHostPort(host string, https bool) (string, string) {
  66. h := host
  67. p := "80"
  68. if https {
  69. p = "443"
  70. }
  71. i := strings.Index(h, ":")
  72. if i > -1 {
  73. p = h[i+1:]
  74. h = h[0:i]
  75. }
  76. return h, p
  77. }
  78. func GetAssetsUrl(filename string) string {
  79. return "/" + filename + "?v=" + consts.AssetsVersion
  80. }
  81. func GetTmplSystemData() consts.TmplSystem {
  82. return consts.TmplSystem{
  83. PathIcoFav: GetAssetsUrl(consts.AssetsSysFaveIco),
  84. PathSvgLogo: GetAssetsUrl(consts.AssetsSysLogoSvg),
  85. PathCssStyles: GetAssetsUrl(consts.AssetsSysStylesCss),
  86. PathCssCpStyles: GetAssetsUrl(consts.AssetsCpStylesCss),
  87. PathCssBootstrap: GetAssetsUrl(consts.AssetsBootstrapCss),
  88. PathJsJquery: GetAssetsUrl(consts.AssetsJqueryJs),
  89. PathJsPopper: GetAssetsUrl(consts.AssetsPopperJs),
  90. PathJsBootstrap: GetAssetsUrl(consts.AssetsBootstrapJs),
  91. PathJsCpScripts: GetAssetsUrl(consts.AssetsCpScriptsJs),
  92. }
  93. }
  94. func GetTmplError(err error) consts.TmplError {
  95. return consts.TmplError{
  96. ErrorMessage: err.Error(),
  97. }
  98. }
  99. func GetMd5(str string) string {
  100. hasher := md5.New()
  101. hasher.Write([]byte(str))
  102. return hex.EncodeToString(hasher.Sum(nil))
  103. }
  104. func GetCurrentUnixTimestamp() int64 {
  105. return int64(time.Now().Unix())
  106. }
  107. func SystemRenderTemplate(w http.ResponseWriter, c []byte, d interface{}) {
  108. tmpl, err := template.New("template").Parse(string(c))
  109. if err != nil {
  110. SystemErrorPageEngine(w, err)
  111. return
  112. }
  113. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  114. w.Header().Set("Content-Type", "text/html")
  115. tmpl.Execute(w, consts.TmplData{
  116. System: GetTmplSystemData(),
  117. Data: d,
  118. })
  119. }
  120. func SystemErrorPageEngine(w http.ResponseWriter, err error) {
  121. if tmpl, e := template.New("template").Parse(string(assets.TmplPageErrorEngine)); e == nil {
  122. w.WriteHeader(http.StatusInternalServerError)
  123. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  124. w.Header().Set("Content-Type", "text/html")
  125. tmpl.Execute(w, consts.TmplData{
  126. System: GetTmplSystemData(),
  127. Data: GetTmplError(err),
  128. })
  129. return
  130. }
  131. w.WriteHeader(http.StatusInternalServerError)
  132. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  133. w.Header().Set("Content-Type", "text/html")
  134. w.Write([]byte("<h1>Critical engine error</h1>"))
  135. w.Write([]byte("<h2>" + err.Error() + "</h2>"))
  136. }
  137. func SystemErrorPage404(w http.ResponseWriter) {
  138. tmpl, err := template.New("template").Parse(string(assets.TmplPageError404))
  139. if err != nil {
  140. SystemErrorPageEngine(w, err)
  141. return
  142. }
  143. w.WriteHeader(http.StatusNotFound)
  144. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  145. w.Header().Set("Content-Type", "text/html")
  146. tmpl.Execute(w, consts.TmplData{
  147. System: GetTmplSystemData(),
  148. Data: nil,
  149. })
  150. }
  151. func UrlToArray(url string) []string {
  152. url_buff := url
  153. if len(url_buff) >= 1 && url_buff[:1] == "/" {
  154. url_buff = url_buff[1:]
  155. }
  156. if len(url_buff) >= 1 && url_buff[len(url_buff)-1:] == "/" {
  157. url_buff = url_buff[:len(url_buff)-1]
  158. }
  159. if url_buff == "" {
  160. return []string{}
  161. } else {
  162. return strings.Split(url_buff, "/")
  163. }
  164. }
  165. func IntToStr(num int) string {
  166. return fmt.Sprintf("%d", num)
  167. }
  168. func StrToInt(str string) int {
  169. num, err := strconv.Atoi(str)
  170. if err == nil {
  171. return num
  172. }
  173. return 0
  174. }
  175. func GenerateAlias(str string) string {
  176. if str == "" {
  177. return ""
  178. }
  179. 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"}
  180. 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"}
  181. var alias string = ""
  182. for i := 0; i < len(str); i++ {
  183. for j := 0; j < len(cyr); j++ {
  184. if string(str[i]) == cyr[j] {
  185. alias += lat[j]
  186. }
  187. }
  188. }
  189. alias = strings.ToLower(alias)
  190. // Cut repeated chars "-"
  191. if reg, err := regexp.Compile("[\\-]+"); err == nil {
  192. alias = strings.Trim(reg.ReplaceAllString(alias, "-"), "-")
  193. }
  194. alias = "/" + alias + "/"
  195. // Cut repeated chars "/"
  196. if reg, err := regexp.Compile("[/]+"); err == nil {
  197. alias = reg.ReplaceAllString(alias, "/")
  198. }
  199. return alias
  200. }
  201. func UnixTimestampToMySqlDateTime(sec int64) string {
  202. return time.Unix(sec, 0).Format("2006-01-02 15:04:05")
  203. }
  204. func UnixTimestampToFormat(sec int64, format string) string {
  205. return time.Unix(sec, 0).Format(format)
  206. }
  207. func ExtractGetParams(str string) string {
  208. i := strings.Index(str, "?")
  209. if i == -1 {
  210. return ""
  211. }
  212. return "?" + str[i+1:]
  213. }