utils.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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. "unicode/utf16"
  14. "golang-fave/assets"
  15. "golang-fave/consts"
  16. )
  17. func IsFileExists(filename string) bool {
  18. if _, err := os.Stat(filename); !os.IsNotExist(err) {
  19. if err == nil {
  20. return true
  21. }
  22. }
  23. return false
  24. }
  25. func IsDir(filename string) bool {
  26. if st, err := os.Stat(filename); !os.IsNotExist(err) {
  27. if err == nil {
  28. if st.Mode().IsDir() {
  29. return true
  30. }
  31. }
  32. }
  33. return false
  34. }
  35. func IsDirExists(path string) bool {
  36. if IsFileExists(path) && IsDir(path) {
  37. return true
  38. }
  39. return false
  40. }
  41. func IsNumeric(str string) bool {
  42. if _, err := strconv.Atoi(str); err == nil {
  43. return true
  44. }
  45. return false
  46. }
  47. func IsValidEmail(email string) bool {
  48. regexpe := regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`)
  49. return regexpe.MatchString(email)
  50. }
  51. func IsValidAlias(alias string) bool {
  52. regexpeSlash := regexp.MustCompile(`[\/]{2,}`)
  53. regexpeChars := regexp.MustCompile(`^\/([a-zA-Z0-9\/\-_\.]+)\/?$`)
  54. return (!regexpeSlash.MatchString(alias) && regexpeChars.MatchString(alias)) || alias == "/"
  55. }
  56. func FixPath(path string) string {
  57. newPath := strings.TrimSpace(path)
  58. if len(newPath) <= 0 {
  59. return newPath
  60. }
  61. if newPath[len(newPath)-1] == '/' || newPath[len(newPath)-1] == '\\' {
  62. newPath = newPath[0 : len(newPath)-1]
  63. }
  64. return newPath
  65. }
  66. func ExtractHostPort(host string, https bool) (string, string) {
  67. h := host
  68. p := "80"
  69. if https {
  70. p = "443"
  71. }
  72. i := strings.Index(h, ":")
  73. if i > -1 {
  74. p = h[i+1:]
  75. h = h[0:i]
  76. }
  77. return h, p
  78. }
  79. func GetAssetsUrl(filename string) string {
  80. return "/" + filename + "?v=" + consts.AssetsVersion
  81. }
  82. func GetTmplSystemData() consts.TmplSystem {
  83. return consts.TmplSystem{
  84. PathIcoFav: GetAssetsUrl(consts.AssetsSysFaveIco),
  85. PathSvgLogo: GetAssetsUrl(consts.AssetsSysLogoSvg),
  86. PathCssStyles: GetAssetsUrl(consts.AssetsSysStylesCss),
  87. PathCssCpStyles: GetAssetsUrl(consts.AssetsCpStylesCss),
  88. PathCssBootstrap: GetAssetsUrl(consts.AssetsBootstrapCss),
  89. PathJsJquery: GetAssetsUrl(consts.AssetsJqueryJs),
  90. PathJsPopper: GetAssetsUrl(consts.AssetsPopperJs),
  91. PathJsBootstrap: GetAssetsUrl(consts.AssetsBootstrapJs),
  92. PathJsCpScripts: GetAssetsUrl(consts.AssetsCpScriptsJs),
  93. PathThemeStyles: "/assets/theme/styles.css",
  94. PathThemeScripts: "/assets/theme/scripts.js",
  95. }
  96. }
  97. func GetTmplError(err error) consts.TmplError {
  98. return consts.TmplError{
  99. ErrorMessage: err.Error(),
  100. }
  101. }
  102. func GetMd5(str string) string {
  103. hasher := md5.New()
  104. hasher.Write([]byte(str))
  105. return hex.EncodeToString(hasher.Sum(nil))
  106. }
  107. func GetCurrentUnixTimestamp() int64 {
  108. return int64(time.Now().Unix())
  109. }
  110. func SystemRenderTemplate(w http.ResponseWriter, c []byte, d interface{}) {
  111. tmpl, err := template.New("template").Parse(string(c))
  112. if err != nil {
  113. SystemErrorPageEngine(w, err)
  114. return
  115. }
  116. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  117. w.Header().Set("Content-Type", "text/html")
  118. tmpl.Execute(w, consts.TmplData{
  119. System: GetTmplSystemData(),
  120. Data: d,
  121. })
  122. }
  123. func SystemErrorPageEngine(w http.ResponseWriter, err error) {
  124. if tmpl, e := template.New("template").Parse(string(assets.TmplPageErrorEngine)); e == nil {
  125. w.WriteHeader(http.StatusInternalServerError)
  126. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  127. w.Header().Set("Content-Type", "text/html")
  128. tmpl.Execute(w, consts.TmplData{
  129. System: GetTmplSystemData(),
  130. Data: GetTmplError(err),
  131. })
  132. return
  133. }
  134. w.WriteHeader(http.StatusInternalServerError)
  135. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  136. w.Header().Set("Content-Type", "text/html")
  137. w.Write([]byte("<h1>Critical engine error</h1>"))
  138. w.Write([]byte("<h2>" + err.Error() + "</h2>"))
  139. }
  140. func SystemErrorPageTemplate(w http.ResponseWriter, err error) {
  141. if tmpl, e := template.New("template").Parse(string(assets.TmplPageErrorTmpl)); e == nil {
  142. w.WriteHeader(http.StatusInternalServerError)
  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: GetTmplError(err),
  148. })
  149. return
  150. }
  151. w.WriteHeader(http.StatusInternalServerError)
  152. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  153. w.Header().Set("Content-Type", "text/html")
  154. w.Write([]byte("<h1>Critical engine error</h1>"))
  155. w.Write([]byte("<h2>" + err.Error() + "</h2>"))
  156. }
  157. func SystemErrorPage404(w http.ResponseWriter) {
  158. tmpl, err := template.New("template").Parse(string(assets.TmplPageError404))
  159. if err != nil {
  160. SystemErrorPageEngine(w, err)
  161. return
  162. }
  163. w.WriteHeader(http.StatusNotFound)
  164. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  165. w.Header().Set("Content-Type", "text/html")
  166. tmpl.Execute(w, consts.TmplData{
  167. System: GetTmplSystemData(),
  168. Data: nil,
  169. })
  170. }
  171. func UrlToArray(url string) []string {
  172. url_buff := url
  173. // Remove GET parameters
  174. i := strings.Index(url_buff, "?")
  175. if i > -1 {
  176. url_buff = url_buff[:i]
  177. }
  178. // Cut slashes
  179. if len(url_buff) >= 1 && url_buff[:1] == "/" {
  180. url_buff = url_buff[1:]
  181. }
  182. if len(url_buff) >= 1 && url_buff[len(url_buff)-1:] == "/" {
  183. url_buff = url_buff[:len(url_buff)-1]
  184. }
  185. // Explode
  186. if url_buff == "" {
  187. return []string{}
  188. } else {
  189. return strings.Split(url_buff, "/")
  190. }
  191. }
  192. func IntToStr(num int) string {
  193. return fmt.Sprintf("%d", num)
  194. }
  195. func StrToInt(str string) int {
  196. num, err := strconv.Atoi(str)
  197. if err == nil {
  198. return num
  199. }
  200. return 0
  201. }
  202. func GenerateAlias(str string) string {
  203. if str == "" {
  204. return ""
  205. }
  206. strc := utf16.Encode([]rune(str))
  207. 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"}
  208. 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"}
  209. var alias string = ""
  210. for i := 0; i < len(strc); i++ {
  211. for j := 0; j < len(cyr); j++ {
  212. if string(strc[i]) == cyr[j] {
  213. alias += lat[j]
  214. }
  215. }
  216. }
  217. alias = strings.ToLower(alias)
  218. // Cut repeated chars "-"
  219. if reg, err := regexp.Compile("[\\-]+"); err == nil {
  220. alias = strings.Trim(reg.ReplaceAllString(alias, "-"), "-")
  221. }
  222. alias = "/" + alias + "/"
  223. // Cut repeated chars "/"
  224. if reg, err := regexp.Compile("[/]+"); err == nil {
  225. alias = reg.ReplaceAllString(alias, "/")
  226. }
  227. return alias
  228. }
  229. func UnixTimestampToMySqlDateTime(sec int64) string {
  230. return time.Unix(sec, 0).Format("2006-01-02 15:04:05")
  231. }
  232. func UnixTimestampToFormat(sec int64, format string) string {
  233. return time.Unix(sec, 0).Format(format)
  234. }
  235. func ExtractGetParams(str string) string {
  236. i := strings.Index(str, "?")
  237. if i == -1 {
  238. return ""
  239. }
  240. return "?" + str[i+1:]
  241. }
  242. func JavaScriptVarValue(str string) string {
  243. return strings.Replace(
  244. strings.Replace(str, `'`, `&rsquo;`, -1),
  245. `"`,
  246. `&rdquo;`,
  247. -1,
  248. )
  249. }