utils.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. }
  94. }
  95. func GetTmplError(err error) consts.TmplError {
  96. return consts.TmplError{
  97. ErrorMessage: err.Error(),
  98. }
  99. }
  100. func GetMd5(str string) string {
  101. hasher := md5.New()
  102. hasher.Write([]byte(str))
  103. return hex.EncodeToString(hasher.Sum(nil))
  104. }
  105. func GetCurrentUnixTimestamp() int64 {
  106. return int64(time.Now().Unix())
  107. }
  108. func SystemRenderTemplate(w http.ResponseWriter, c []byte, d interface{}) {
  109. tmpl, err := template.New("template").Parse(string(c))
  110. if err != nil {
  111. SystemErrorPageEngine(w, err)
  112. return
  113. }
  114. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  115. w.Header().Set("Content-Type", "text/html")
  116. tmpl.Execute(w, consts.TmplData{
  117. System: GetTmplSystemData(),
  118. Data: d,
  119. })
  120. }
  121. func SystemErrorPageEngine(w http.ResponseWriter, err error) {
  122. if tmpl, e := template.New("template").Parse(string(assets.TmplPageErrorEngine)); e == nil {
  123. w.WriteHeader(http.StatusInternalServerError)
  124. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  125. w.Header().Set("Content-Type", "text/html")
  126. tmpl.Execute(w, consts.TmplData{
  127. System: GetTmplSystemData(),
  128. Data: GetTmplError(err),
  129. })
  130. return
  131. }
  132. w.WriteHeader(http.StatusInternalServerError)
  133. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  134. w.Header().Set("Content-Type", "text/html")
  135. w.Write([]byte("<h1>Critical engine error</h1>"))
  136. w.Write([]byte("<h2>" + err.Error() + "</h2>"))
  137. }
  138. func SystemErrorPageTemplate(w http.ResponseWriter, err error) {
  139. if tmpl, e := template.New("template").Parse(string(assets.TmplPageErrorTmpl)); e == nil {
  140. w.WriteHeader(http.StatusInternalServerError)
  141. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  142. w.Header().Set("Content-Type", "text/html")
  143. tmpl.Execute(w, consts.TmplData{
  144. System: GetTmplSystemData(),
  145. Data: GetTmplError(err),
  146. })
  147. return
  148. }
  149. w.WriteHeader(http.StatusInternalServerError)
  150. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  151. w.Header().Set("Content-Type", "text/html")
  152. w.Write([]byte("<h1>Critical engine error</h1>"))
  153. w.Write([]byte("<h2>" + err.Error() + "</h2>"))
  154. }
  155. func SystemErrorPage404(w http.ResponseWriter) {
  156. tmpl, err := template.New("template").Parse(string(assets.TmplPageError404))
  157. if err != nil {
  158. SystemErrorPageEngine(w, err)
  159. return
  160. }
  161. w.WriteHeader(http.StatusNotFound)
  162. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  163. w.Header().Set("Content-Type", "text/html")
  164. tmpl.Execute(w, consts.TmplData{
  165. System: GetTmplSystemData(),
  166. Data: nil,
  167. })
  168. }
  169. func UrlToArray(url string) []string {
  170. url_buff := url
  171. // Remove GET parameters
  172. i := strings.Index(url_buff, "?")
  173. if i > -1 {
  174. url_buff = url_buff[:i]
  175. }
  176. // Cut slashes
  177. if len(url_buff) >= 1 && url_buff[:1] == "/" {
  178. url_buff = url_buff[1:]
  179. }
  180. if len(url_buff) >= 1 && url_buff[len(url_buff)-1:] == "/" {
  181. url_buff = url_buff[:len(url_buff)-1]
  182. }
  183. // Explode
  184. if url_buff == "" {
  185. return []string{}
  186. } else {
  187. return strings.Split(url_buff, "/")
  188. }
  189. }
  190. func IntToStr(num int) string {
  191. return fmt.Sprintf("%d", num)
  192. }
  193. func StrToInt(str string) int {
  194. num, err := strconv.Atoi(str)
  195. if err == nil {
  196. return num
  197. }
  198. return 0
  199. }
  200. func GenerateAlias(str string) string {
  201. if str == "" {
  202. return ""
  203. }
  204. strc := utf16.Encode([]rune(str))
  205. 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"}
  206. 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"}
  207. var alias string = ""
  208. for i := 0; i < len(strc); i++ {
  209. for j := 0; j < len(cyr); j++ {
  210. if string(strc[i]) == cyr[j] {
  211. alias += lat[j]
  212. }
  213. }
  214. }
  215. alias = strings.ToLower(alias)
  216. // Cut repeated chars "-"
  217. if reg, err := regexp.Compile("[\\-]+"); err == nil {
  218. alias = strings.Trim(reg.ReplaceAllString(alias, "-"), "-")
  219. }
  220. alias = "/" + alias + "/"
  221. // Cut repeated chars "/"
  222. if reg, err := regexp.Compile("[/]+"); err == nil {
  223. alias = reg.ReplaceAllString(alias, "/")
  224. }
  225. return alias
  226. }
  227. func UnixTimestampToMySqlDateTime(sec int64) string {
  228. return time.Unix(sec, 0).Format("2006-01-02 15:04:05")
  229. }
  230. func UnixTimestampToFormat(sec int64, format string) string {
  231. return time.Unix(sec, 0).Format(format)
  232. }
  233. func ExtractGetParams(str string) string {
  234. i := strings.Index(str, "?")
  235. if i == -1 {
  236. return ""
  237. }
  238. return "?" + str[i+1:]
  239. }
  240. func JavaScriptVarValue(str string) string {
  241. return strings.Replace(
  242. strings.Replace(str, `'`, `&rsquo;`, -1),
  243. `"`,
  244. `&rdquo;`,
  245. -1,
  246. )
  247. }