utils.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. package utils
  2. import (
  3. "crypto/md5"
  4. "database/sql"
  5. "encoding/hex"
  6. "fmt"
  7. "html/template"
  8. "math"
  9. "net/http"
  10. "os"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "unicode/utf16"
  16. "golang-fave/assets"
  17. "golang-fave/consts"
  18. )
  19. func IsFileExists(filename string) bool {
  20. if _, err := os.Stat(filename); !os.IsNotExist(err) {
  21. if err == nil {
  22. return true
  23. }
  24. }
  25. return false
  26. }
  27. func IsDir(filename string) bool {
  28. if st, err := os.Stat(filename); !os.IsNotExist(err) {
  29. if err == nil {
  30. if st.Mode().IsDir() {
  31. return true
  32. }
  33. }
  34. }
  35. return false
  36. }
  37. func IsDirExists(path string) bool {
  38. if IsFileExists(path) && IsDir(path) {
  39. return true
  40. }
  41. return false
  42. }
  43. func IsNumeric(str string) bool {
  44. if _, err := strconv.Atoi(str); err == nil {
  45. return true
  46. }
  47. return false
  48. }
  49. func IsFloat(str string) bool {
  50. if _, err := strconv.ParseFloat(str, 64); err == nil {
  51. return true
  52. }
  53. return false
  54. }
  55. func IsValidMobile(str string) bool {
  56. regexpeChars := regexp.MustCompile(`^\+([1-9]{1})([0-9]{1})([0-9]{3})([0-9]{7})$`)
  57. return regexpeChars.MatchString(str)
  58. }
  59. func IsValidEmail(email string) bool {
  60. regexpe := regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`)
  61. return regexpe.MatchString(email)
  62. }
  63. func IsValidAlias(alias string) bool {
  64. // Control panel
  65. regexpeCP := regexp.MustCompile(`^\/cp\/`)
  66. if alias == "/cp" || regexpeCP.MatchString(alias) {
  67. return false
  68. }
  69. // Blog module
  70. regexpeBlog := regexp.MustCompile(`^\/blog\/`)
  71. if alias == "/blog" || regexpeBlog.MatchString(alias) {
  72. return false
  73. }
  74. // Shop module
  75. regexpeShop := regexp.MustCompile(`^\/shop\/`)
  76. if alias == "/shop" || regexpeShop.MatchString(alias) {
  77. return false
  78. }
  79. // API module
  80. regexpeApi := regexp.MustCompile(`^\/api\/`)
  81. if alias == "/api" || regexpeApi.MatchString(alias) {
  82. return false
  83. }
  84. regexpeSlash := regexp.MustCompile(`[\/]{2,}`)
  85. regexpeChars := regexp.MustCompile(`^\/([a-zA-Z0-9\/\-_\.]+)\/?$`)
  86. return (!regexpeSlash.MatchString(alias) && regexpeChars.MatchString(alias)) || alias == "/"
  87. }
  88. func IsValidSingleAlias(alias string) bool {
  89. regexpeChars := regexp.MustCompile(`^([a-zA-Z0-9\-_]{1,})$`)
  90. return regexpeChars.MatchString(alias)
  91. }
  92. func FixPath(path string) string {
  93. newPath := strings.TrimSpace(path)
  94. if len(newPath) <= 0 {
  95. return newPath
  96. }
  97. if newPath[len(newPath)-1] == '/' || newPath[len(newPath)-1] == '\\' {
  98. newPath = newPath[0 : len(newPath)-1]
  99. }
  100. return newPath
  101. }
  102. func ExtractHostPort(host string, https bool) (string, string) {
  103. h := host
  104. p := "80"
  105. if https {
  106. p = "443"
  107. }
  108. i := strings.Index(h, ":")
  109. if i > -1 {
  110. p = h[i+1:]
  111. h = h[0:i]
  112. }
  113. return h, p
  114. }
  115. func GetAssetsUrl(filename string) string {
  116. return "/" + filename + "?v=" + consts.ServerVersion
  117. }
  118. func GetTmplSystemData(cpmod, cpsubmod string) consts.TmplSystem {
  119. return consts.TmplSystem{
  120. CpSubModule: cpsubmod,
  121. InfoVersion: consts.ServerVersion,
  122. PathCssBootstrap: GetAssetsUrl(consts.AssetsBootstrapCss),
  123. PathCssCpCodeMirror: GetAssetsUrl(consts.AssetsCpCodeMirrorCss),
  124. PathCssCpStyles: GetAssetsUrl(consts.AssetsCpStylesCss),
  125. PathCssCpWysiwygPell: GetAssetsUrl(consts.AssetsCpWysiwygPellCss),
  126. PathCssLightGallery: GetAssetsUrl(consts.AssetsLightGalleryCss),
  127. PathCssStyles: GetAssetsUrl(consts.AssetsSysStylesCss),
  128. PathIcoFav: GetAssetsUrl(consts.AssetsSysFaveIco),
  129. PathJsBootstrap: GetAssetsUrl(consts.AssetsBootstrapJs),
  130. PathJsCpCodeMirror: GetAssetsUrl(consts.AssetsCpCodeMirrorJs),
  131. PathJsCpScripts: GetAssetsUrl(consts.AssetsCpScriptsJs),
  132. PathJsCpWysiwygPell: GetAssetsUrl(consts.AssetsCpWysiwygPellJs),
  133. PathJsJquery: GetAssetsUrl(consts.AssetsJqueryJs),
  134. PathJsLightGallery: GetAssetsUrl(consts.AssetsLightGalleryJs),
  135. PathJsPopper: GetAssetsUrl(consts.AssetsPopperJs),
  136. PathSvgLogo: GetAssetsUrl(consts.AssetsSysLogoSvg),
  137. PathThemeScripts: "/assets/theme/scripts.js?v=" + consts.ServerVersion,
  138. PathThemeStyles: "/assets/theme/styles.css?v=" + consts.ServerVersion,
  139. CpModule: cpmod,
  140. }
  141. }
  142. func GetTmplError(err error) consts.TmplError {
  143. return consts.TmplError{
  144. ErrorMessage: err.Error(),
  145. }
  146. }
  147. func GetMd5(str string) string {
  148. hasher := md5.New()
  149. hasher.Write([]byte(str))
  150. return hex.EncodeToString(hasher.Sum(nil))
  151. }
  152. func GetCurrentUnixTimestamp() int64 {
  153. return int64(time.Now().Unix())
  154. }
  155. func SystemRenderTemplate(w http.ResponseWriter, c []byte, d interface{}, cpmod, cpsubmod string) {
  156. tmpl, err := template.New("template").Parse(string(c))
  157. if err != nil {
  158. SystemErrorPageEngine(w, err)
  159. return
  160. }
  161. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  162. w.Header().Set("Content-Type", "text/html")
  163. tmpl.Execute(w, consts.TmplData{
  164. System: GetTmplSystemData(cpmod, cpsubmod),
  165. Data: d,
  166. })
  167. }
  168. func SystemErrorPageEngine(w http.ResponseWriter, err error) {
  169. if tmpl, e := template.New("template").Parse(string(assets.TmplPageErrorEngine)); e == nil {
  170. w.WriteHeader(http.StatusInternalServerError)
  171. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  172. w.Header().Set("Content-Type", "text/html")
  173. tmpl.Execute(w, consts.TmplData{
  174. System: GetTmplSystemData("error", "engine"),
  175. Data: GetTmplError(err),
  176. })
  177. return
  178. }
  179. w.WriteHeader(http.StatusInternalServerError)
  180. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  181. w.Header().Set("Content-Type", "text/html")
  182. w.Write([]byte("<h1>Critical engine error</h1>"))
  183. w.Write([]byte("<h2>" + err.Error() + "</h2>"))
  184. }
  185. func SystemErrorPageTemplate(w http.ResponseWriter, err error) {
  186. if tmpl, e := template.New("template").Parse(string(assets.TmplPageErrorTmpl)); e == nil {
  187. w.WriteHeader(http.StatusInternalServerError)
  188. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  189. w.Header().Set("Content-Type", "text/html")
  190. tmpl.Execute(w, consts.TmplData{
  191. System: GetTmplSystemData("error", "template"),
  192. Data: GetTmplError(err),
  193. })
  194. return
  195. }
  196. w.WriteHeader(http.StatusInternalServerError)
  197. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  198. w.Header().Set("Content-Type", "text/html")
  199. w.Write([]byte("<h1>Critical engine error</h1>"))
  200. w.Write([]byte("<h2>" + err.Error() + "</h2>"))
  201. }
  202. func SystemErrorPage404(w http.ResponseWriter) {
  203. tmpl, err := template.New("template").Parse(string(assets.TmplPageError404))
  204. if err != nil {
  205. SystemErrorPageEngine(w, err)
  206. return
  207. }
  208. w.WriteHeader(http.StatusNotFound)
  209. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  210. w.Header().Set("Content-Type", "text/html")
  211. tmpl.Execute(w, consts.TmplData{
  212. System: GetTmplSystemData("error", "404"),
  213. Data: nil,
  214. })
  215. }
  216. func UrlToArray(url string) []string {
  217. url_buff := url
  218. // Remove GET parameters
  219. i := strings.Index(url_buff, "?")
  220. if i > -1 {
  221. url_buff = url_buff[:i]
  222. }
  223. // Cut slashes
  224. if len(url_buff) >= 1 && url_buff[:1] == "/" {
  225. url_buff = url_buff[1:]
  226. }
  227. if len(url_buff) >= 1 && url_buff[len(url_buff)-1:] == "/" {
  228. url_buff = url_buff[:len(url_buff)-1]
  229. }
  230. // Explode
  231. if url_buff == "" {
  232. return []string{}
  233. } else {
  234. return strings.Split(url_buff, "/")
  235. }
  236. }
  237. func IntToStr(num int) string {
  238. return fmt.Sprintf("%d", num)
  239. }
  240. func Int64ToStr(num int64) string {
  241. return fmt.Sprintf("%d", num)
  242. }
  243. func StrToInt(str string) int {
  244. num, err := strconv.Atoi(str)
  245. if err == nil {
  246. return num
  247. }
  248. return 0
  249. }
  250. func Float64ToStr(num float64) string {
  251. return fmt.Sprintf("%.2f", num)
  252. }
  253. func Float64ToStrF(num float64, format string) string {
  254. return fmt.Sprintf(format, num)
  255. }
  256. func StrToFloat64(str string) float64 {
  257. num, err := strconv.ParseFloat(str, 64)
  258. if err == nil {
  259. return num
  260. }
  261. return 0
  262. }
  263. func GenerateAlias(str string) string {
  264. if str == "" {
  265. return ""
  266. }
  267. strc := utf16.Encode([]rune(str))
  268. 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"}
  269. 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"}
  270. var alias string = ""
  271. for i := 0; i < len(strc); i++ {
  272. for j := 0; j < len(cyr); j++ {
  273. if string(strc[i]) == cyr[j] {
  274. alias += lat[j]
  275. }
  276. }
  277. }
  278. alias = strings.ToLower(alias)
  279. // Cut repeated chars "-"
  280. if reg, err := regexp.Compile("[\\-]+"); err == nil {
  281. alias = strings.Trim(reg.ReplaceAllString(alias, "-"), "-")
  282. }
  283. alias = "/" + alias + "/"
  284. // Cut repeated chars "/"
  285. if reg, err := regexp.Compile("[/]+"); err == nil {
  286. alias = reg.ReplaceAllString(alias, "/")
  287. }
  288. return alias
  289. }
  290. func GenerateSingleAlias(str string) string {
  291. alias := GenerateAlias(str)
  292. if len(alias) > 1 && alias[0] == '/' {
  293. alias = alias[1:]
  294. }
  295. if len(alias) > 1 && alias[len(alias)-1] == '/' {
  296. alias = alias[:len(alias)-1]
  297. }
  298. return alias
  299. }
  300. func UnixTimestampToMySqlDateTime(sec int64) string {
  301. return time.Unix(sec, 0).Format("2006-01-02 15:04:05")
  302. }
  303. func UnixTimestampToFormat(sec int64, format string) string {
  304. return time.Unix(sec, 0).Format(format)
  305. }
  306. func ExtractGetParams(str string) string {
  307. i := strings.Index(str, "?")
  308. if i == -1 {
  309. return ""
  310. }
  311. return "?" + str[i+1:]
  312. }
  313. func JavaScriptVarValue(str string) string {
  314. return strings.Replace(
  315. strings.Replace(str, `'`, `&rsquo;`, -1),
  316. `"`,
  317. `&rdquo;`,
  318. -1,
  319. )
  320. }
  321. func InArrayInt(slice []int, value int) bool {
  322. for _, item := range slice {
  323. if item == value {
  324. return true
  325. }
  326. }
  327. return false
  328. }
  329. func InArrayString(slice []string, value string) bool {
  330. for _, item := range slice {
  331. if item == value {
  332. return true
  333. }
  334. }
  335. return false
  336. }
  337. func GetPostArrayInt(name string, r *http.Request) []int {
  338. var ids []int
  339. if arr, ok := r.PostForm[name]; ok {
  340. for _, el := range arr {
  341. if IsNumeric(el) {
  342. if !InArrayInt(ids, StrToInt(el)) {
  343. ids = append(ids, StrToInt(el))
  344. }
  345. }
  346. }
  347. }
  348. return ids
  349. }
  350. func GetPostArrayString(name string, r *http.Request) []string {
  351. var ids []string
  352. if arr, ok := r.PostForm[name]; ok {
  353. for _, el := range arr {
  354. if !InArrayString(ids, el) {
  355. ids = append(ids, el)
  356. }
  357. }
  358. }
  359. return ids
  360. }
  361. func ArrayOfIntToArrayOfString(arr []int) []string {
  362. var res []string
  363. for _, el := range arr {
  364. res = append(res, IntToStr(el))
  365. }
  366. return res
  367. }
  368. func ArrayOfStringToArrayOfInt(arr []string) []int {
  369. var res []int
  370. for _, el := range arr {
  371. if IsNumeric(el) {
  372. res = append(res, StrToInt(el))
  373. }
  374. }
  375. return res
  376. }
  377. func TemplateAdditionalFuncs() template.FuncMap {
  378. return template.FuncMap{
  379. "plus": func(a, b int) int {
  380. return a + b
  381. },
  382. "minus": func(a, b int) int {
  383. return a - b
  384. },
  385. "multiply": func(a, b int) int {
  386. return a * b
  387. },
  388. "divide": func(a, b int) int {
  389. return a / b
  390. },
  391. "repeat": func(a string, n int) template.HTML {
  392. out := ""
  393. for i := 1; i <= n; i++ {
  394. out += a
  395. }
  396. return template.HTML(out)
  397. },
  398. }
  399. }
  400. func SqlNullStringToString(arr *[]sql.NullString) *[]string {
  401. values := make([]string, len(*arr))
  402. for key, value := range *arr {
  403. values[key] = value.String
  404. }
  405. return &values
  406. }
  407. func GetImagePlaceholderSrc() string {
  408. return "/" + consts.AssetsSysPlaceholderPng
  409. }
  410. func FormatProductPrice(price float64, format, round int) string {
  411. p := price
  412. if round == 1 {
  413. p = math.Ceil(p)
  414. } else if round == 2 {
  415. p = math.Floor(p)
  416. }
  417. if format == 1 {
  418. return Float64ToStrF(p, "%.1f")
  419. } else if format == 2 {
  420. return Float64ToStrF(p, "%.2f")
  421. } else if format == 3 {
  422. return Float64ToStrF(p, "%.3f")
  423. } else if format == 4 {
  424. return Float64ToStrF(p, "%.4f")
  425. }
  426. return Float64ToStrF(p, "%.0f")
  427. }