common.go 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653
  1. package utils
  2. import (
  3. "bufio"
  4. "bytes"
  5. "crypto/hmac"
  6. "crypto/md5"
  7. "crypto/sha1"
  8. "crypto/sha256"
  9. "encoding/base64"
  10. "encoding/hex"
  11. "encoding/json"
  12. "errors"
  13. "fmt"
  14. "html"
  15. "image"
  16. "image/png"
  17. "io"
  18. "math"
  19. "math/rand"
  20. "net"
  21. "net/http"
  22. "net/url"
  23. "os"
  24. "os/exec"
  25. "path"
  26. "regexp"
  27. "sort"
  28. "strconv"
  29. "strings"
  30. "time"
  31. "unicode"
  32. "github.com/PuerkitoBio/goquery"
  33. "github.com/microcosm-cc/bluemonday"
  34. "github.com/shopspring/decimal"
  35. xhtml "golang.org/x/net/html"
  36. )
  37. // 随机数种子
  38. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  39. func GetRandString(size int) string {
  40. allLetterDigit := []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "!", "@", "#", "$", "%", "^", "&", "*"}
  41. randomSb := ""
  42. digitSize := len(allLetterDigit)
  43. for i := 0; i < size; i++ {
  44. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  45. }
  46. return randomSb
  47. }
  48. func GetRandStringNoSpecialChar(size int) string {
  49. allLetterDigit := []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
  50. randomSb := ""
  51. digitSize := len(allLetterDigit)
  52. for i := 0; i < size; i++ {
  53. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  54. }
  55. return randomSb
  56. }
  57. func StringsToJSON(str string) string {
  58. rs := []rune(str)
  59. jsons := ""
  60. for _, r := range rs {
  61. rint := int(r)
  62. if rint < 128 {
  63. jsons += string(r)
  64. } else {
  65. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  66. }
  67. }
  68. return jsons
  69. }
  70. // 序列化
  71. func ToString(v interface{}) string {
  72. data, _ := json.Marshal(v)
  73. return string(data)
  74. }
  75. // md5加密
  76. func MD5(data string) string {
  77. m := md5.Sum([]byte(data))
  78. return hex.EncodeToString(m[:])
  79. }
  80. // HmacMd5 HmacMd5加密
  81. func HmacMd5(key, data string) string {
  82. h := hmac.New(md5.New, []byte(key))
  83. h.Write([]byte(data))
  84. return hex.EncodeToString(h.Sum([]byte("")))
  85. }
  86. // 获取数字随机字符
  87. func GetRandDigit(n int) string {
  88. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  89. }
  90. // 获取随机数
  91. func GetRandNumber(n int) int {
  92. return rnd.Intn(n)
  93. }
  94. func GetRandInt(min, max int) int {
  95. if min >= max || min == 0 || max == 0 {
  96. return max
  97. }
  98. return rand.Intn(max-min) + min
  99. }
  100. func GetToday(format string) string {
  101. today := time.Now().Format(format)
  102. return today
  103. }
  104. // 获取今天剩余秒数
  105. func GetTodayLastSecond() time.Duration {
  106. today := GetToday(FormatDate) + " 23:59:59"
  107. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  108. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  109. }
  110. // 处理出生日期函数
  111. func GetBrithDate(idcard string) string {
  112. l := len(idcard)
  113. var s string
  114. if l == 15 {
  115. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  116. return s
  117. }
  118. if l == 18 {
  119. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  120. return s
  121. }
  122. return GetToday(FormatDate)
  123. }
  124. // 处理性别
  125. func WhichSexByIdcard(idcard string) string {
  126. var sexs = [2]string{"女", "男"}
  127. length := len(idcard)
  128. if length == 18 {
  129. sex, _ := strconv.Atoi(string(idcard[16]))
  130. return sexs[sex%2]
  131. } else if length == 15 {
  132. sex, _ := strconv.Atoi(string(idcard[14]))
  133. return sexs[sex%2]
  134. }
  135. return "男"
  136. }
  137. // SubFloatToString 截取小数点后几位
  138. func SubFloatToString(f float64, m int) string {
  139. n := strconv.FormatFloat(f, 'f', -1, 64)
  140. if n == "" {
  141. return ""
  142. }
  143. if m >= len(n) {
  144. return n
  145. }
  146. newn := strings.Split(n, ".")
  147. if m == 0 {
  148. return newn[0]
  149. }
  150. if len(newn) < 2 || m >= len(newn[1]) {
  151. return n
  152. }
  153. return newn[0] + "." + newn[1][:m]
  154. }
  155. // 截取小数点后几位
  156. func SubFloatToFloat(f float64, m int) float64 {
  157. newn := SubFloatToString(f, m)
  158. newf, _ := strconv.ParseFloat(newn, 64)
  159. return newf
  160. }
  161. // 截取小数点后几位
  162. func SubFloatToFloatStr(f float64, m int) string {
  163. newn := SubFloatToString(f, m)
  164. return newn
  165. }
  166. // 获取相差时间-年
  167. func GetYearDiffer(start_time, end_time string) int {
  168. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  169. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  170. age := t2.Year() - t1.Year()
  171. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  172. age--
  173. }
  174. return age
  175. }
  176. // 获取相差时间-秒
  177. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  178. diff := end_time.Unix() - start_time.Unix()
  179. return diff
  180. }
  181. func FixFloat(f float64, m int) float64 {
  182. newn := SubFloatToString(f+0.00000001, m)
  183. newf, _ := strconv.ParseFloat(newn, 64)
  184. return newf
  185. }
  186. // 将字符串数组转化为逗号分割的字符串形式 ["str1","str2","str3"] >>> "str1,str2,str3"
  187. func StrListToString(strList []string) (str string) {
  188. if len(strList) > 0 {
  189. for k, v := range strList {
  190. if k == 0 {
  191. str = v
  192. } else {
  193. str = str + "," + v
  194. }
  195. }
  196. return
  197. }
  198. return ""
  199. }
  200. // 数据没有记录
  201. func ErrNoRow() string {
  202. return "<QuerySeter> no row found"
  203. }
  204. // 校验邮箱格式
  205. func ValidateEmailFormatat(email string) bool {
  206. reg := regexp.MustCompile(RegularEmail)
  207. return reg.MatchString(email)
  208. }
  209. // 验证是否是手机号
  210. func ValidateMobileFormatat(mobileNum string) bool {
  211. reg := regexp.MustCompile(RegularMobile)
  212. return reg.MatchString(mobileNum)
  213. }
  214. // 判断文件是否存在
  215. func FileIsExist(filePath string) bool {
  216. _, err := os.Stat(filePath)
  217. return err == nil || os.IsExist(err)
  218. }
  219. // 获取图片扩展名
  220. func GetImgExt(file string) (ext string, err error) {
  221. var headerByte []byte
  222. headerByte = make([]byte, 8)
  223. fd, err := os.Open(file)
  224. if err != nil {
  225. return "", err
  226. }
  227. defer fd.Close()
  228. _, err = fd.Read(headerByte)
  229. if err != nil {
  230. return "", err
  231. }
  232. xStr := fmt.Sprintf("%x", headerByte)
  233. switch {
  234. case xStr == "89504e470d0a1a0a":
  235. ext = ".png"
  236. case xStr == "0000010001002020":
  237. ext = ".ico"
  238. case xStr == "0000020001002020":
  239. ext = ".cur"
  240. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  241. ext = ".gif"
  242. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  243. ext = ".tga"
  244. case xStr[:8] == "464f524d":
  245. ext = ".iff"
  246. case xStr[:8] == "52494646":
  247. ext = ".ani"
  248. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  249. ext = ".tiff"
  250. case xStr[:4] == "424d":
  251. ext = ".bmp"
  252. case xStr[:4] == "ffd8":
  253. ext = ".jpg"
  254. case xStr[:2] == "0a":
  255. ext = ".pcx"
  256. default:
  257. ext = ""
  258. }
  259. return ext, nil
  260. }
  261. // 保存图片
  262. func SaveImage(path string, img image.Image) (err error) {
  263. //需要保持的文件
  264. imgfile, err := os.Create(path)
  265. defer imgfile.Close()
  266. // 以PNG格式保存文件
  267. err = png.Encode(imgfile, img)
  268. return err
  269. }
  270. // 下载图片
  271. func DownloadImage(imgUrl string) (filePath string, err error) {
  272. imgPath := "./static/imgs/"
  273. fileName := path.Base(imgUrl)
  274. res, err := http.Get(imgUrl)
  275. if err != nil {
  276. fmt.Println("A error occurred!")
  277. return
  278. }
  279. defer res.Body.Close()
  280. // 获得get请求响应的reader对象
  281. reader := bufio.NewReaderSize(res.Body, 32*1024)
  282. filePath = imgPath + fileName
  283. file, err := os.Create(filePath)
  284. if err != nil {
  285. return
  286. }
  287. defer func() {
  288. file.Close()
  289. }()
  290. // 获得文件的writer对象
  291. writer := bufio.NewWriter(file)
  292. written, _ := io.Copy(writer, reader)
  293. fmt.Printf("Total length: %d \n", written)
  294. return
  295. }
  296. // DownloadFile 下载文件
  297. func DownloadFile(fileUrl, fileDir string) (filePath string, err error) {
  298. filePathDir := "./static/imgs/"
  299. if fileDir != `` {
  300. err = os.MkdirAll(fileDir, DIR_MOD)
  301. if err != nil {
  302. return
  303. }
  304. filePathDir = fileDir
  305. }
  306. fileName := path.Base(fileUrl)
  307. res, err := http.Get(fileUrl)
  308. if err != nil {
  309. fmt.Println("A error occurred!")
  310. return
  311. }
  312. defer res.Body.Close()
  313. // 获得get请求响应的reader对象
  314. reader := bufio.NewReaderSize(res.Body, 32*1024)
  315. filePath = filePathDir + GetRandString(4) + fileName
  316. file, err := os.Create(filePath)
  317. if err != nil {
  318. return
  319. }
  320. defer func() {
  321. file.Close()
  322. }()
  323. // 获得文件的writer对象
  324. writer := bufio.NewWriter(file)
  325. _, _ = io.Copy(writer, reader)
  326. //fmt.Printf("Total length: %d \n", written)
  327. return
  328. }
  329. // 保存base64数据为文件
  330. func SaveBase64ToFile(content, path string) error {
  331. data, err := base64.StdEncoding.DecodeString(content)
  332. if err != nil {
  333. return err
  334. }
  335. f, err := os.Create(path)
  336. defer f.Close()
  337. if err != nil {
  338. return err
  339. }
  340. f.Write(data)
  341. return nil
  342. }
  343. func SaveBase64ToFileBySeek(content, path string) (err error) {
  344. data, err := base64.StdEncoding.DecodeString(content)
  345. exist, err := PathExists(path)
  346. if err != nil {
  347. return
  348. }
  349. if !exist {
  350. f, err := os.Create(path)
  351. if err != nil {
  352. return err
  353. }
  354. n, _ := f.Seek(0, 2)
  355. // 从末尾的偏移量开始写入内容
  356. _, err = f.WriteAt([]byte(data), n)
  357. defer f.Close()
  358. } else {
  359. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  360. if err != nil {
  361. return err
  362. }
  363. n, _ := f.Seek(0, 2)
  364. // 从末尾的偏移量开始写入内容
  365. _, err = f.WriteAt([]byte(data), n)
  366. defer f.Close()
  367. }
  368. return nil
  369. }
  370. func PathExists(path string) (bool, error) {
  371. _, err := os.Stat(path)
  372. if err == nil {
  373. return true, nil
  374. }
  375. if os.IsNotExist(err) {
  376. return false, nil
  377. }
  378. return false, err
  379. }
  380. func StartIndex(page, pagesize int) int {
  381. if page > 1 {
  382. return (page - 1) * pagesize
  383. }
  384. return 0
  385. }
  386. func PageCount(count, pagesize int) int {
  387. if count%pagesize > 0 {
  388. return count/pagesize + 1
  389. } else {
  390. return count / pagesize
  391. }
  392. }
  393. func TrimHtml(src string) string {
  394. //将HTML标签全转换成小写
  395. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  396. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  397. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  398. src = re.ReplaceAllString(src, "")
  399. re, _ = regexp.Compile("class[\\S\\s]+?>")
  400. src = re.ReplaceAllString(src, "")
  401. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  402. src = re.ReplaceAllString(src, "")
  403. src = strings.ReplaceAll(src, "&nbsp;", " ")
  404. return strings.TrimSpace(src)
  405. }
  406. //1556164246 -> 2019-04-25 03:50:46 +0000
  407. //timestamp
  408. func TimeToTimestamp() {
  409. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  410. }
  411. func ToUnicode(text string) string {
  412. textQuoted := strconv.QuoteToASCII(text)
  413. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  414. return textUnquoted
  415. }
  416. func VersionToInt(version string) int {
  417. version = strings.Replace(version, ".", "", -1)
  418. n, _ := strconv.Atoi(version)
  419. return n
  420. }
  421. func IsCheckInList(list []int, s int) bool {
  422. for _, v := range list {
  423. if v == s {
  424. return true
  425. }
  426. }
  427. return false
  428. }
  429. func round(num float64) int {
  430. return int(num + math.Copysign(0.5, num))
  431. }
  432. func toFixed(num float64, precision int) float64 {
  433. output := math.Pow(10, float64(precision))
  434. return float64(round(num*output)) / output
  435. }
  436. // GetWilsonScore returns Wilson Score
  437. func GetWilsonScore(p, n float64) float64 {
  438. if p == 0 && n == 0 {
  439. return 0
  440. }
  441. return toFixed(((p+1.9208)/(p+n)-1.96*math.Sqrt(p*n/(p+n)+0.9604)/(p+n))/(1+3.8416/(p+n)), 2)
  442. }
  443. // 将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
  444. func ChangeWordsToNum(str string) (numStr string) {
  445. words := ([]rune)(str)
  446. num := 0
  447. n := 0
  448. for i := 0; i < len(words); i++ {
  449. word := string(words[i : i+1])
  450. switch word {
  451. case "万":
  452. if n == 0 {
  453. n = 1
  454. }
  455. n = n * 10000
  456. num = num*10000 + n
  457. n = 0
  458. case "千":
  459. if n == 0 {
  460. n = 1
  461. }
  462. n = n * 1000
  463. num += n
  464. n = 0
  465. case "百":
  466. if n == 0 {
  467. n = 1
  468. }
  469. n = n * 100
  470. num += n
  471. n = 0
  472. case "十":
  473. if n == 0 {
  474. n = 1
  475. }
  476. n = n * 10
  477. num += n
  478. n = 0
  479. case "一":
  480. n += 1
  481. case "二":
  482. n += 2
  483. case "三":
  484. n += 3
  485. case "四":
  486. n += 4
  487. case "五":
  488. n += 5
  489. case "六":
  490. n += 6
  491. case "七":
  492. n += 7
  493. case "八":
  494. n += 8
  495. case "九":
  496. n += 9
  497. case "零":
  498. default:
  499. if n > 0 {
  500. num += n
  501. n = 0
  502. }
  503. if num == 0 {
  504. numStr += word
  505. } else {
  506. numStr += strconv.Itoa(num) + word
  507. num = 0
  508. }
  509. }
  510. }
  511. if n > 0 {
  512. num += n
  513. n = 0
  514. }
  515. if num != 0 {
  516. numStr += strconv.Itoa(num)
  517. }
  518. return
  519. }
  520. func Sha1(data string) string {
  521. sha1 := sha1.New()
  522. sha1.Write([]byte(data))
  523. return hex.EncodeToString(sha1.Sum([]byte("")))
  524. }
  525. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  526. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  527. out, err := exec.Command("bash", "-c", cmd).Output()
  528. if err != nil {
  529. return
  530. }
  531. outTimes := string(out)
  532. fmt.Println("outTimes:", outTimes)
  533. if outTimes != "" {
  534. timeArr := strings.Split(outTimes, ":")
  535. h := timeArr[0]
  536. m := timeArr[1]
  537. s := timeArr[2]
  538. hInt, err := strconv.Atoi(h)
  539. if err != nil {
  540. return playSeconds, err
  541. }
  542. mInt, err := strconv.Atoi(m)
  543. if err != nil {
  544. return playSeconds, err
  545. }
  546. s = strings.Trim(s, " ")
  547. s = strings.Trim(s, "\n")
  548. sInt, err := strconv.ParseFloat(s, 64)
  549. if err != nil {
  550. return playSeconds, err
  551. }
  552. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  553. }
  554. return
  555. }
  556. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  557. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  558. tradeCode = strings.Trim(tradeCode, " ")
  559. tradeCodeInt, err := strconv.Atoi(tradeCode)
  560. if err != nil {
  561. return
  562. }
  563. tradeCodeInt = tradeCodeInt + 1
  564. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  565. return
  566. }
  567. func GetTradeCodeList(tradeCode string, num int) (tradeCodeList []string, err error) {
  568. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  569. tradeCode = strings.Trim(tradeCode, " ")
  570. tradeCodeInt, err := strconv.Atoi(tradeCode)
  571. if err != nil {
  572. return
  573. }
  574. for i := 0; i < num; i++ {
  575. tradeCodeInt = tradeCodeInt + 1
  576. tradeCodeList = append(tradeCodeList, fmt.Sprintf("W%06d", tradeCodeInt))
  577. }
  578. return
  579. }
  580. // excel日期字段格式化 yyyy-mm-dd
  581. func ConvertToFormatDay(excelDaysString string) string {
  582. // 2006-01-02 距离 1900-01-01的天数
  583. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  584. curDiffDay := excelDaysString
  585. b, _ := strconv.Atoi(curDiffDay)
  586. // 获取excel的日期距离2006-01-02的天数
  587. realDiffDay := b - baseDiffDay
  588. //fmt.Println("realDiffDay:",realDiffDay)
  589. // 距离2006-01-02 秒数
  590. realDiffSecond := realDiffDay * 24 * 3600
  591. //fmt.Println("realDiffSecond:",realDiffSecond)
  592. // 2006-01-02 15:04:05距离1970-01-01 08:00:00的秒数 网上工具可查出
  593. baseOriginSecond := 1136185445
  594. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  595. return resultTime
  596. }
  597. // GetDaysDiff1900 计算日期距离1900-01-01的天数
  598. func GetDaysDiff1900(date string) int {
  599. // 将字符串转换为时间类型
  600. //从1899年12月30日开始是因为Excel的日期计算是基于1900年1月1日的,而1900年并不是闰年,因此Excel日期计算存在一个错误。为了修正这个错误,
  601. //我们将时间回溯到1899年12月30日,这样在进行日期计算时可以正确地处理Excel日期。
  602. tStart, err := time.ParseInLocation(FormatDate, "1899-12-30", time.Local)
  603. if err != nil {
  604. return 0
  605. }
  606. tEnd, err := time.ParseInLocation(FormatDate, date, time.Local)
  607. if err != nil {
  608. return 0
  609. }
  610. // 计算两个日期之间的天数差值
  611. duration := tEnd.Sub(tStart).Hours() / 24
  612. days := int(duration)
  613. return days
  614. }
  615. func CheckPwd(pwd string) bool {
  616. compile := `([0-9a-z]+){6,12}|(a-z0-9]+){6,12}`
  617. reg := regexp.MustCompile(compile)
  618. flag := reg.MatchString(pwd)
  619. return flag
  620. }
  621. func GetMonthStartAndEnd(myYear string, myMonth string) (startDate, endDate string) {
  622. // 数字月份必须前置补零
  623. if len(myMonth) == 1 {
  624. myMonth = "0" + myMonth
  625. }
  626. yInt, _ := strconv.Atoi(myYear)
  627. timeLayout := "2006-01-02 15:04:05"
  628. loc, _ := time.LoadLocation("Local")
  629. theTime, _ := time.ParseInLocation(timeLayout, myYear+"-"+myMonth+"-01 00:00:00", loc)
  630. newMonth := theTime.Month()
  631. t1 := time.Date(yInt, newMonth, 1, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  632. t2 := time.Date(yInt, newMonth+1, 0, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  633. return t1, t2
  634. }
  635. // TrimStr 移除字符串中的空格
  636. func TrimStr(str string) (str2 string) {
  637. if str == "" {
  638. return str
  639. }
  640. return strings.Replace(str, " ", "", -1)
  641. }
  642. // TrimLRStr 移除字符串前后的空格
  643. func TrimLRStr(str string) (str2 string) {
  644. if str == "" {
  645. return str
  646. }
  647. str2 = strings.TrimLeft(str, " ")
  648. str2 = strings.TrimRight(str2, " ")
  649. return
  650. }
  651. // 字符串转换为time
  652. func StrTimeToTime(strTime string) time.Time {
  653. timeLayout := "2006-01-02 15:04:05" //转化所需模板
  654. loc, _ := time.LoadLocation("Local") //重要:获取时区
  655. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  656. return resultTime
  657. }
  658. // TimeToStr time.Time 转 字符串 yyyy-MM-dd
  659. func TimeToStr(data time.Time, format string) string {
  660. return data.Format(format)
  661. }
  662. // 字符串类型时间转周几
  663. func StrDateTimeToWeek(strTime string) string {
  664. var WeekDayMap = map[string]string{
  665. "Monday": "周一",
  666. "Tuesday": "周二",
  667. "Wednesday": "周三",
  668. "Thursday": "周四",
  669. "Friday": "周五",
  670. "Saturday": "周六",
  671. "Sunday": "周日",
  672. }
  673. var ctime = StrTimeToTime(strTime).Format("2006-01-02")
  674. startday, _ := time.Parse("2006-01-02", ctime)
  675. staweek_int := startday.Weekday().String()
  676. return WeekDayMap[staweek_int]
  677. }
  678. // EnWeekToCnWeek 英文周几转中文周几
  679. func EnWeekToCnWeek(enWeekStr string) string {
  680. var WeekDayMap = map[string]string{
  681. "Monday": "周一",
  682. "Tuesday": "周二",
  683. "Wednesday": "周三",
  684. "Thursday": "周四",
  685. "Friday": "周五",
  686. "Saturday": "周六",
  687. "Sunday": "周日",
  688. }
  689. cnWeekStr, ok := WeekDayMap[enWeekStr]
  690. if !ok {
  691. cnWeekStr = `周一`
  692. }
  693. return cnWeekStr
  694. }
  695. // 时间格式转年月日字符串
  696. func TimeToStrYmd(time2 time.Time) string {
  697. var Ymd string
  698. year := time2.Year()
  699. month := time2.Format("1")
  700. day1 := time.Now().Day()
  701. Ymd = strconv.Itoa(year) + "年" + month + "月" + strconv.Itoa(day1) + "日"
  702. return Ymd
  703. }
  704. // 时间格式去掉时分秒
  705. func TimeRemoveHms(strTime string) string {
  706. var Ymd string
  707. var resultTime = StrTimeToTime(strTime)
  708. year := resultTime.Year()
  709. month := resultTime.Format("01")
  710. day1 := resultTime.Day()
  711. if day1 < 10 {
  712. Ymd = strconv.Itoa(year) + "." + month + ".0" + strconv.Itoa(day1)
  713. } else {
  714. Ymd = strconv.Itoa(year) + "." + month + "." + strconv.Itoa(day1)
  715. }
  716. return Ymd
  717. }
  718. // 时间格式去掉时分秒
  719. func TimeRemoveHms2(strTime string) string {
  720. var Ymd string
  721. var resultTime = StrTimeToTime(strTime)
  722. year := resultTime.Year()
  723. month := resultTime.Format("01")
  724. day1 := resultTime.Day()
  725. if day1 < 10 {
  726. Ymd = strconv.Itoa(year) + "-" + month + "-0" + strconv.Itoa(day1)
  727. } else {
  728. Ymd = strconv.Itoa(year) + "-" + month + "-" + strconv.Itoa(day1)
  729. }
  730. return Ymd
  731. }
  732. // 文章上一次编辑时间
  733. func ArticleLastTime(strTime string) string {
  734. var newTime string
  735. stamp, _ := time.ParseInLocation("2006-01-02 15:04:05", strTime, time.Local)
  736. diffTime := time.Now().Unix() - stamp.Unix()
  737. if diffTime <= 60 {
  738. newTime = "当前"
  739. } else if diffTime < 60*60 {
  740. newTime = strconv.FormatInt(diffTime/60, 10) + "分钟前"
  741. } else if diffTime < 24*60*60 {
  742. newTime = strconv.FormatInt(diffTime/(60*60), 10) + "小时前"
  743. } else if diffTime < 30*24*60*60 {
  744. newTime = strconv.FormatInt(diffTime/(24*60*60), 10) + "天前"
  745. } else if diffTime < 12*30*24*60*60 {
  746. newTime = strconv.FormatInt(diffTime/(30*24*60*60), 10) + "月前"
  747. } else {
  748. newTime = "1年前"
  749. }
  750. return newTime
  751. }
  752. // 人民币小写转大写
  753. func ConvertNumToCny(num float64) (str string, err error) {
  754. strNum := strconv.FormatFloat(num*100, 'f', 0, 64)
  755. sliceUnit := []string{"仟", "佰", "拾", "亿", "仟", "佰", "拾", "万", "仟", "佰", "拾", "元", "角", "分"}
  756. // log.Println(sliceUnit[:len(sliceUnit)-2])
  757. s := sliceUnit[len(sliceUnit)-len(strNum):]
  758. upperDigitUnit := map[string]string{"0": "零", "1": "壹", "2": "贰", "3": "叁", "4": "肆", "5": "伍", "6": "陆", "7": "柒", "8": "捌", "9": "玖"}
  759. for k, v := range strNum[:] {
  760. str = str + upperDigitUnit[string(v)] + s[k]
  761. }
  762. reg, err := regexp.Compile(`零角零分$`)
  763. str = reg.ReplaceAllString(str, "整")
  764. reg, err = regexp.Compile(`零角`)
  765. str = reg.ReplaceAllString(str, "零")
  766. reg, err = regexp.Compile(`零分$`)
  767. str = reg.ReplaceAllString(str, "整")
  768. reg, err = regexp.Compile(`零[仟佰拾]`)
  769. str = reg.ReplaceAllString(str, "零")
  770. reg, err = regexp.Compile(`零{2,}`)
  771. str = reg.ReplaceAllString(str, "零")
  772. reg, err = regexp.Compile(`零亿`)
  773. str = reg.ReplaceAllString(str, "亿")
  774. reg, err = regexp.Compile(`零万`)
  775. str = reg.ReplaceAllString(str, "万")
  776. reg, err = regexp.Compile(`零*元`)
  777. str = reg.ReplaceAllString(str, "元")
  778. reg, err = regexp.Compile(`亿零{0, 3}万`)
  779. str = reg.ReplaceAllString(str, "^元")
  780. reg, err = regexp.Compile(`零元`)
  781. str = reg.ReplaceAllString(str, "零")
  782. return
  783. }
  784. // GetNowWeekMonday 获取本周周一的时间
  785. func GetNowWeekMonday() time.Time {
  786. offset := int(time.Monday - time.Now().Weekday())
  787. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  788. offset = -6
  789. }
  790. mondayTime := time.Now().AddDate(0, 0, offset)
  791. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  792. return mondayTime
  793. }
  794. // GetNowWeekLastDay 获取本周最后一天的时间
  795. func GetNowWeekLastDay() time.Time {
  796. offset := int(time.Monday - time.Now().Weekday())
  797. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  798. offset = -6
  799. }
  800. firstDayTime := time.Now().AddDate(0, 0, offset)
  801. firstDayTime = time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 0, 0, 0, 0, firstDayTime.Location()).AddDate(0, 0, 6)
  802. lastDayTime := time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 23, 59, 59, 0, firstDayTime.Location())
  803. return lastDayTime
  804. }
  805. // GetNowMonthFirstDay 获取本月第一天的时间
  806. func GetNowMonthFirstDay() time.Time {
  807. nowMonthFirstDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location())
  808. return nowMonthFirstDay
  809. }
  810. // GetNowMonthLastDay 获取本月最后一天的时间
  811. func GetNowMonthLastDay() time.Time {
  812. nowMonthLastDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  813. nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
  814. return nowMonthLastDay
  815. }
  816. // GetNowQuarterFirstDay 获取本季度第一天的时间
  817. func GetNowQuarterFirstDay() time.Time {
  818. month := int(time.Now().Month())
  819. var nowQuarterFirstDay time.Time
  820. if month >= 1 && month <= 3 {
  821. //1月1号
  822. nowQuarterFirstDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  823. } else if month >= 4 && month <= 6 {
  824. //4月1号
  825. nowQuarterFirstDay = time.Date(time.Now().Year(), 4, 1, 0, 0, 0, 0, time.Now().Location())
  826. } else if month >= 7 && month <= 9 {
  827. nowQuarterFirstDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  828. } else {
  829. nowQuarterFirstDay = time.Date(time.Now().Year(), 10, 1, 0, 0, 0, 0, time.Now().Location())
  830. }
  831. return nowQuarterFirstDay
  832. }
  833. // GetNowQuarterLastDay 获取本季度最后一天的时间
  834. func GetNowQuarterLastDay() time.Time {
  835. month := int(time.Now().Month())
  836. var nowQuarterLastDay time.Time
  837. if month >= 1 && month <= 3 {
  838. //03-31 23:59:59
  839. nowQuarterLastDay = time.Date(time.Now().Year(), 3, 31, 23, 59, 59, 0, time.Now().Location())
  840. } else if month >= 4 && month <= 6 {
  841. //06-30 23:59:59
  842. nowQuarterLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  843. } else if month >= 7 && month <= 9 {
  844. //09-30 23:59:59
  845. nowQuarterLastDay = time.Date(time.Now().Year(), 9, 30, 23, 59, 59, 0, time.Now().Location())
  846. } else {
  847. //12-31 23:59:59
  848. nowQuarterLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  849. }
  850. return nowQuarterLastDay
  851. }
  852. // GetNowHalfYearFirstDay 获取当前半年的第一天的时间
  853. func GetNowHalfYearFirstDay() time.Time {
  854. month := int(time.Now().Month())
  855. var nowHalfYearLastDay time.Time
  856. if month >= 1 && month <= 6 {
  857. //03-31 23:59:59
  858. nowHalfYearLastDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  859. } else {
  860. //12-31 23:59:59
  861. nowHalfYearLastDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  862. }
  863. return nowHalfYearLastDay
  864. }
  865. // GetNowHalfYearLastDay 获取当前半年的最后一天的时间
  866. func GetNowHalfYearLastDay() time.Time {
  867. month := int(time.Now().Month())
  868. var nowHalfYearLastDay time.Time
  869. if month >= 1 && month <= 6 {
  870. //03-31 23:59:59
  871. nowHalfYearLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  872. } else {
  873. //12-31 23:59:59
  874. nowHalfYearLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  875. }
  876. return nowHalfYearLastDay
  877. }
  878. // GetNowYearFirstDay 获取当前年的最后一天的时间
  879. func GetNowYearFirstDay() time.Time {
  880. //12-31 23:59:59
  881. nowYearFirstDay := time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  882. return nowYearFirstDay
  883. }
  884. // GetNowYearLastDay 获取当前年的最后一天的时间
  885. func GetNowYearLastDay() time.Time {
  886. //12-31 23:59:59
  887. nowYearLastDay := time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  888. return nowYearLastDay
  889. }
  890. // CalculationDate 计算两个日期之间相差n年m月y天
  891. func CalculationDate(startDate, endDate time.Time) (beetweenDay string, err error) {
  892. //startDate := time.Date(2021, 3, 28, 0, 0, 0, 0, time.Now().Location())
  893. //endDate := time.Date(2022, 3, 31, 0, 0, 0, 0, time.Now().Location())
  894. numYear := endDate.Year() - startDate.Year()
  895. numMonth := int(endDate.Month()) - int(startDate.Month())
  896. numDay := 0
  897. //获取截止月的总天数
  898. endDateDays := getMonthDay(endDate.Year(), int(endDate.Month()))
  899. //获取截止月的前一个月
  900. endDatePrevMonthDate := endDate.AddDate(0, -1, 0)
  901. //获取截止日期的上一个月的总天数
  902. endDatePrevMonthDays := getMonthDay(endDatePrevMonthDate.Year(), int(endDatePrevMonthDate.Month()))
  903. //获取开始日期的的月份总天数
  904. startDateMonthDays := getMonthDay(startDate.Year(), int(startDate.Month()))
  905. //判断,截止月是否完全被选中,如果相等,那么代表截止月份全部天数被选择
  906. if endDate.Day() == endDateDays {
  907. numDay = startDateMonthDays - startDate.Day() + 1
  908. //如果剩余天数正好与开始日期的天数是一致的,那么月份加1
  909. if numDay == startDateMonthDays {
  910. numMonth++
  911. numDay = 0
  912. //超过月份了,那么年份加1
  913. if numMonth == 12 {
  914. numYear++
  915. numMonth = 0
  916. }
  917. }
  918. } else {
  919. numDay = endDate.Day() - startDate.Day() + 1
  920. }
  921. //天数小于0,那么向月份借一位
  922. if numDay < 0 {
  923. //向上一个月借一个月的天数
  924. numDay += endDatePrevMonthDays
  925. //总月份减去一个月
  926. numMonth = numMonth - 1
  927. }
  928. //月份小于0,那么向年份借一位
  929. if numMonth < 0 {
  930. //向上一个年借12个月
  931. numMonth += 12
  932. //总年份减去一年
  933. numYear = numYear - 1
  934. }
  935. if numYear < 0 {
  936. err = errors.New("日期异常")
  937. return
  938. }
  939. if numYear > 0 {
  940. beetweenDay += fmt.Sprint(numYear, "年")
  941. }
  942. if numMonth > 0 {
  943. beetweenDay += fmt.Sprint(numMonth, "个月")
  944. }
  945. if numDay > 0 {
  946. beetweenDay += fmt.Sprint(numDay, "天")
  947. }
  948. return
  949. }
  950. // FormatPrice 格式化展示金额数字(财务金额展示,小数点前,每三位用,隔开) 1,234,567,898.55
  951. func FormatPrice(price float64) (str string) {
  952. str = decimal.NewFromFloat(price).String()
  953. length := len(str)
  954. if length < 4 {
  955. return str
  956. }
  957. arr := strings.Split(str, ".") //用小数点符号分割字符串,为数组接收
  958. length1 := len(arr[0])
  959. if length1 < 4 {
  960. return str
  961. }
  962. count := (length1 - 1) / 3
  963. for i := 0; i < count; i++ {
  964. arr[0] = arr[0][:length1-(i+1)*3] + "," + arr[0][length1-(i+1)*3:]
  965. }
  966. return strings.Join(arr, ".") //将一系列字符串连接为一个字符串,之间用sep来分隔。
  967. }
  968. // getMonthDay 获取某年某月有多少天
  969. func getMonthDay(year, month int) (days int) {
  970. if month != 2 {
  971. if month == 4 || month == 6 || month == 9 || month == 11 {
  972. days = 30
  973. } else {
  974. days = 31
  975. }
  976. } else {
  977. if ((year%4) == 0 && (year%100) != 0) || (year%400) == 0 {
  978. days = 29
  979. } else {
  980. days = 28
  981. }
  982. }
  983. return
  984. }
  985. func SaveToFile(content, path string) error {
  986. f, err := os.Create(path)
  987. defer f.Close()
  988. if err != nil {
  989. return err
  990. }
  991. f.Write([]byte(content))
  992. return nil
  993. }
  994. // 用户参会时间转换
  995. func GetAttendanceDetailSeconds(secondNum int) string {
  996. var timeStr string
  997. if secondNum <= 60 {
  998. if secondNum < 10 {
  999. timeStr = "0" + strconv.Itoa(secondNum) + "''"
  1000. } else {
  1001. timeStr = strconv.Itoa(secondNum) + "''"
  1002. }
  1003. } else {
  1004. var remainderStr string
  1005. remainderNum := secondNum % 60
  1006. minuteNum := secondNum / 60
  1007. if remainderNum < 10 {
  1008. remainderStr = "0" + strconv.Itoa(remainderNum) + "''"
  1009. } else {
  1010. remainderStr = strconv.Itoa(remainderNum) + "''"
  1011. }
  1012. if minuteNum < 10 {
  1013. timeStr = "0" + strconv.Itoa(minuteNum) + "'" + remainderStr
  1014. } else {
  1015. timeStr = strconv.Itoa(minuteNum) + "'" + remainderStr
  1016. }
  1017. }
  1018. return timeStr
  1019. }
  1020. // SubStr 截取字符串(中文)
  1021. func SubStr(str string, subLen int) string {
  1022. strRune := []rune(str)
  1023. bodyRuneLen := len(strRune)
  1024. if bodyRuneLen > subLen {
  1025. bodyRuneLen = subLen
  1026. }
  1027. str = string(strRune[:bodyRuneLen])
  1028. return str
  1029. }
  1030. // HideString 给字段加***(从字符串中间替换,少于需要替换的长度,那么就补全*的长度)
  1031. // src 待*字符串
  1032. // hideLen 需要加*的长度
  1033. func HideString(src string, hideLen int) string {
  1034. if src == "" {
  1035. return src
  1036. }
  1037. str := []rune(src)
  1038. if hideLen == 0 {
  1039. hideLen = 4
  1040. }
  1041. hideStr := ""
  1042. for i := 0; i < hideLen; i++ {
  1043. hideStr += "*"
  1044. }
  1045. strLen := len(str)
  1046. // 字符长度是1
  1047. if strLen == 1 {
  1048. return string(str[:1]) + hideStr
  1049. }
  1050. //字符长度大于1,但是小于等于需要隐藏的字符长度,那么就隐藏中间,保留前后各一位字符
  1051. if strLen <= hideLen+2 {
  1052. return string(str[:1]) + hideStr + string(str[strLen-1:])
  1053. }
  1054. subLen := strLen - hideLen //剩余需要展示的字符长度
  1055. decimal.NewFromFloat(2)
  1056. frontLenDecimal := decimal.NewFromInt(int64(subLen)).Div(decimal.NewFromInt(2)) //前面需要展示的字符的长度
  1057. frontLen := frontLenDecimal.Floor().IntPart()
  1058. return string(str[:frontLen]) + hideStr + string(str[frontLen+int64(hideLen):])
  1059. }
  1060. func GetLocalIP() (ip string, err error) {
  1061. addrs, err := net.InterfaceAddrs()
  1062. if err != nil {
  1063. return
  1064. }
  1065. for _, addr := range addrs {
  1066. ipAddr, ok := addr.(*net.IPNet)
  1067. if !ok {
  1068. continue
  1069. }
  1070. if ipAddr.IP.IsLoopback() {
  1071. continue
  1072. }
  1073. if !ipAddr.IP.IsGlobalUnicast() {
  1074. continue
  1075. }
  1076. return ipAddr.IP.String(), nil
  1077. }
  1078. return
  1079. }
  1080. // GetNowWeekMonday 获取上一周周一的时间
  1081. func GetPreWeekMonday() time.Time {
  1082. nowMonday := GetNowWeekMonday()
  1083. return nowMonday.AddDate(0, 0, -7)
  1084. }
  1085. // GetNowWeekLastDay 获取上一周最后一天的时间
  1086. func GetPreWeekLastDay() time.Time {
  1087. nowSunday := GetNowWeekLastDay()
  1088. return nowSunday.AddDate(0, 0, -7)
  1089. }
  1090. // GetNextWeekMonday 获取下一周周一的时间
  1091. func GetNextWeekMonday() time.Time {
  1092. nowMonday := GetNowWeekMonday()
  1093. return nowMonday.AddDate(0, 0, 7)
  1094. }
  1095. // GetNextWeekLastDay 获取下一周最后一天的时间
  1096. func GetNextWeekLastDay() time.Time {
  1097. nowSunday := GetNowWeekLastDay()
  1098. return nowSunday.AddDate(0, 0, 7)
  1099. }
  1100. // 处理真实姓名,隐藏中间的部分,如:张*,张*将
  1101. func DealRealName(realName string) string {
  1102. if realName == "" {
  1103. return ""
  1104. }
  1105. names := bytes.Runes([]byte(realName))
  1106. fistName := names[0]
  1107. length := len(names)
  1108. if length == 2 {
  1109. return string(fistName) + "*"
  1110. } else if length > 2 {
  1111. lastName := names[length-1]
  1112. return string(fistName) + "*" + string(lastName)
  1113. }
  1114. return realName
  1115. }
  1116. // Implode php中的implode(用来将int型的切片转为string)
  1117. func Implode(idIntList []int) (str string) {
  1118. for _, id := range idIntList {
  1119. str += fmt.Sprint(id, ",")
  1120. }
  1121. str = str[:len(str)-1]
  1122. return
  1123. }
  1124. // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该int值)
  1125. func InArrayByInt(idIntList []int, searchId int) (has bool) {
  1126. for _, id := range idIntList {
  1127. if id == searchId {
  1128. has = true
  1129. return
  1130. }
  1131. }
  1132. return
  1133. }
  1134. // InArrayByStr php中的in_array(判断String类型的切片中是否存在该string值)
  1135. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  1136. for _, id := range idStrList {
  1137. if id == searchId {
  1138. has = true
  1139. return
  1140. }
  1141. }
  1142. return
  1143. }
  1144. // Intersection 求两个切片的交集
  1145. func Intersection(a []string, b []string) (inter []string) {
  1146. // interacting on the smallest list first can potentailly be faster...but not by much, worse case is the same
  1147. low, high := a, b
  1148. if len(a) > len(b) {
  1149. low = b
  1150. high = a
  1151. }
  1152. done := false
  1153. for i, l := range low {
  1154. for j, h := range high {
  1155. // get future index values
  1156. f1 := i + 1
  1157. f2 := j + 1
  1158. if l == h {
  1159. inter = append(inter, h)
  1160. if f1 < len(low) && f2 < len(high) {
  1161. // if the future values aren't the same then that's the end of the intersection
  1162. if low[f1] != high[f2] {
  1163. done = true
  1164. }
  1165. }
  1166. // we don't want to interate on the entire list everytime, so remove the parts we already looped on will make it faster each pass
  1167. high = high[:j+copy(high[j:], high[j+1:])]
  1168. break
  1169. }
  1170. }
  1171. // nothing in the future so we are done
  1172. if done {
  1173. break
  1174. }
  1175. }
  1176. return
  1177. }
  1178. // Minus 获取差集
  1179. func Minus(a []string, b []string) []string {
  1180. //var inter []string
  1181. inter := make([]string, 0)
  1182. mp := make(map[string]bool)
  1183. for _, s := range a {
  1184. if _, ok := mp[s]; !ok {
  1185. mp[s] = true
  1186. }
  1187. }
  1188. for _, s := range b {
  1189. if _, ok := mp[s]; ok {
  1190. delete(mp, s)
  1191. }
  1192. }
  1193. for key := range mp {
  1194. inter = append(inter, key)
  1195. }
  1196. return inter
  1197. }
  1198. // IntArr2joinString []int转字符串
  1199. func IntArr2joinString(arr []int, sep string) string {
  1200. if len(arr) == 0 {
  1201. return ""
  1202. }
  1203. strArr := make([]string, 0)
  1204. for _, v := range arr {
  1205. strArr = append(strArr, strconv.Itoa(v))
  1206. }
  1207. return strings.Join(strArr, sep)
  1208. }
  1209. // GetOneMonthFirstDay 获取某月的第一天的时间
  1210. func GetOneMonthFirstDay(time2 time.Time) time.Time {
  1211. nowMonthFirstDay := time.Date(time2.Year(), time2.Month(), 1, 0, 0, 0, 0, time.Now().Location())
  1212. return nowMonthFirstDay
  1213. }
  1214. // GetOneMonthLastDay 获取某月最后一天的时间
  1215. func GetOneMonthLastDay(time2 time.Time) time.Time {
  1216. nowMonthLastDay := time.Date(time2.Year(), time2.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1217. nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
  1218. return nowMonthLastDay
  1219. }
  1220. func GetReportContentTextSub(content string) (contentSub string, err error) {
  1221. content = html.UnescapeString(content)
  1222. doc, err := goquery.NewDocumentFromReader(strings.NewReader(content))
  1223. docText := doc.Text()
  1224. bodyRune := []rune(docText)
  1225. bodyRuneLen := len(bodyRune)
  1226. if bodyRuneLen > 200 {
  1227. bodyRuneLen = 200
  1228. }
  1229. body := string(bodyRune[:bodyRuneLen])
  1230. contentSub = body
  1231. contentSub = strings.Replace(body, "Powered by Froala Editor", "", -1)
  1232. return
  1233. }
  1234. // GetOrmInReplace 获取orm的in查询替换?的方法
  1235. func GetOrmInReplace(num int) string {
  1236. template := make([]string, num)
  1237. for i := 0; i < num; i++ {
  1238. template[i] = "?"
  1239. }
  1240. return strings.Join(template, ",")
  1241. }
  1242. // RevSlice 反转切片
  1243. func RevSlice(slice []int) []int {
  1244. for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
  1245. slice[i], slice[j] = slice[j], slice[i]
  1246. }
  1247. return slice
  1248. }
  1249. // ReplaceSpaceAndWrap 去除空格跟换行
  1250. func ReplaceSpaceAndWrap(str string) string {
  1251. // 去除空格
  1252. str = strings.Replace(str, " ", "", -1)
  1253. // 去除换行符
  1254. str = strings.Replace(str, "\n", "", -1)
  1255. return str
  1256. }
  1257. // JoinStr2IntArr 拼接字符串转[]int
  1258. func JoinStr2IntArr(str, sep string) (arr []int) {
  1259. arr = make([]int, 0)
  1260. if str == "" {
  1261. return
  1262. }
  1263. if sep == "" {
  1264. sep = ","
  1265. }
  1266. strArr := strings.Split(str, sep)
  1267. if len(strArr) == 0 {
  1268. return
  1269. }
  1270. for i := range strArr {
  1271. v, e := strconv.Atoi(strArr[i])
  1272. // int2str此处过滤掉无效int
  1273. if e != nil {
  1274. continue
  1275. }
  1276. arr = append(arr, v)
  1277. }
  1278. return
  1279. }
  1280. // 字符串转换为time类型
  1281. func StrDateToDate(strTime string) time.Time {
  1282. timeLayout := "2006-01-02" //转化所需模板
  1283. loc, _ := time.LoadLocation("Local") //重要:获取时区
  1284. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  1285. return resultTime
  1286. }
  1287. // GetTimeSubDay 计算两个时间的自然日期差(后面减去前面)
  1288. func GetTimeSubDay(t1, t2 time.Time) int {
  1289. var day int
  1290. swap := false
  1291. if t1.Unix() > t2.Unix() {
  1292. t1, t2 = t2, t1
  1293. swap = true
  1294. }
  1295. t1_ := t1.Add(time.Duration(t2.Sub(t1).Milliseconds()%86400000) * time.Millisecond)
  1296. day = int(t2.Sub(t1).Hours() / 24)
  1297. // 计算在t1+两个时间的余数之后天数是否有变化
  1298. if t1_.Day() != t1.Day() {
  1299. day += 1
  1300. }
  1301. if swap {
  1302. day = -day
  1303. }
  1304. return day
  1305. }
  1306. // 去除非中文字符串
  1307. func StrFilterNonChinese(src *string) {
  1308. var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$")
  1309. strn := ""
  1310. for _, c := range *src {
  1311. if hzRegexp.MatchString(string(c)) {
  1312. strn += string(c)
  1313. }
  1314. }
  1315. *src = strn
  1316. }
  1317. // MinusInt 获取两个[]int差集
  1318. func MinusInt(a []int, b []int) []int {
  1319. var diff []int
  1320. mpA, mpB := make(map[int]bool), make(map[int]bool)
  1321. for _, v := range a {
  1322. mpA[v] = true
  1323. }
  1324. for _, v := range b {
  1325. mpB[v] = true
  1326. }
  1327. for _, s := range a {
  1328. if !mpB[s] {
  1329. diff = append(diff, s)
  1330. }
  1331. }
  1332. for _, s := range b {
  1333. if !mpA[s] {
  1334. diff = append(diff, s)
  1335. }
  1336. }
  1337. return diff
  1338. }
  1339. // IntersectInt 获取两个[]int交集
  1340. func IntersectInt(nums1 []int, nums2 []int) []int {
  1341. m := make(map[int]int)
  1342. var res []int
  1343. for _, num := range nums1 {
  1344. m[num]++
  1345. }
  1346. for _, num := range nums2 {
  1347. if m[num] > 0 {
  1348. res = append(res, num)
  1349. m[num]--
  1350. }
  1351. }
  1352. return res
  1353. }
  1354. // MapSorter 对于map 排序
  1355. type MapSorter []Item
  1356. type Item struct {
  1357. Key int
  1358. Val float64
  1359. }
  1360. func NewMapSorter(m map[int]float64) MapSorter {
  1361. ms := make(MapSorter, 0, len(m))
  1362. for k, v := range m {
  1363. ms = append(ms, Item{k, v})
  1364. }
  1365. return ms
  1366. }
  1367. func (ms MapSorter) Len() int {
  1368. return len(ms)
  1369. }
  1370. func (ms MapSorter) Less(i, j int) bool {
  1371. return ms[i].Val > ms[j].Val // 按值排序
  1372. //return ms[i].Key < ms[j].Key // 按键排序
  1373. }
  1374. func (ms MapSorter) Swap(i, j int) {
  1375. ms[i], ms[j] = ms[j], ms[i]
  1376. }
  1377. // FormatFileSize 字节的单位转换 保留两位小数
  1378. func FormatFileSize(fileSize int64) (size string) {
  1379. if fileSize < 1024 {
  1380. return fmt.Sprintf("%.2fB", float64(fileSize)/float64(1))
  1381. } else if fileSize < (1024 * 1024) {
  1382. return fmt.Sprintf("%.2fKB", float64(fileSize)/float64(1024))
  1383. } else if fileSize < (1024 * 1024 * 1024) {
  1384. return fmt.Sprintf("%.2fMB", float64(fileSize)/float64(1024*1024))
  1385. } else if fileSize < (1024 * 1024 * 1024 * 1024) {
  1386. return fmt.Sprintf("%.2fGB", float64(fileSize)/float64(1024*1024*1024))
  1387. } else if fileSize < (1024 * 1024 * 1024 * 1024 * 1024) {
  1388. return fmt.Sprintf("%.2fTB", float64(fileSize)/float64(1024*1024*1024*1024))
  1389. } else { //if fileSize < (1024 * 1024 * 1024 * 1024 * 1024 * 1024)
  1390. return fmt.Sprintf("%.2fPB", float64(fileSize)/float64(1024*1024*1024*1024*1024))
  1391. }
  1392. }
  1393. func GetDurationFormatBySecond(sec int) (formatString string) {
  1394. if sec == 0 {
  1395. formatString = "0分钟"
  1396. return
  1397. } else if sec <= 60 && sec > 0 {
  1398. formatString = "1分钟"
  1399. return
  1400. }
  1401. duration := time.Duration(int64(sec)) * time.Second
  1402. h := int(duration.Hours())
  1403. m := int(duration.Minutes()) % 60
  1404. //s := int(duration.Seconds()) % 60
  1405. if h > 0 {
  1406. formatString = fmt.Sprintf("%d小时", h)
  1407. }
  1408. if m > 0 {
  1409. formatString += fmt.Sprintf("%d分钟", m)
  1410. }
  1411. //if s > 0 {
  1412. // formatString += fmt.Sprintf("%d秒", s)
  1413. //}
  1414. return
  1415. }
  1416. // GetDaysBetween2Date 计算两个日期之间相差几天
  1417. func GetDaysBetween2Date(format, date1Str, date2Str string) (int, error) {
  1418. // 将字符串转化为Time格式
  1419. date1, err := time.ParseInLocation(format, date1Str, time.Local)
  1420. if err != nil {
  1421. return 0, err
  1422. }
  1423. // 将字符串转化为Time格式
  1424. date2, err := time.ParseInLocation(format, date2Str, time.Local)
  1425. if err != nil {
  1426. return 0, err
  1427. }
  1428. //计算相差天数
  1429. return int(date1.Sub(date2).Hours() / 24), nil
  1430. }
  1431. // GetFrequencyEn 获取频度的英文版
  1432. func GetFrequencyEn(frequency string) (frequencyEn string) {
  1433. switch frequency {
  1434. case "日度":
  1435. frequencyEn = "day"
  1436. return
  1437. case "周度":
  1438. frequencyEn = "week"
  1439. return
  1440. case "旬度":
  1441. frequencyEn = "ten days"
  1442. return
  1443. case "月度":
  1444. frequencyEn = "month"
  1445. return
  1446. case "季度":
  1447. frequencyEn = "quarter"
  1448. return
  1449. case "年度":
  1450. frequencyEn = "year"
  1451. return
  1452. }
  1453. return
  1454. }
  1455. // GetLeadUnitEn 获取移动单位的英文版
  1456. func GetLeadUnitEn(unit string) (unitEn string) {
  1457. switch unit {
  1458. case "天":
  1459. unitEn = "day"
  1460. return
  1461. case "周":
  1462. unitEn = "week"
  1463. return
  1464. case "月":
  1465. unitEn = "month"
  1466. return
  1467. case "季":
  1468. unitEn = "quarter"
  1469. return
  1470. case "年":
  1471. unitEn = "year"
  1472. return
  1473. }
  1474. return
  1475. }
  1476. // GetDateByDateType 通过dateType获取需要的开始/结束日期
  1477. // dateType 日期类型:1:00年至今,2:10年至今,3:15年至今,4:年初至今,5:自定义时间,6:起始日期至今 20:最近N年
  1478. func GetDateByDateType(dateType int, tmpStartDate, tmpEndDate string) (startDate, endDate string) {
  1479. startDate = tmpStartDate
  1480. endDate = tmpEndDate
  1481. switch dateType {
  1482. case 1:
  1483. startDate = "2000-01-01"
  1484. endDate = ""
  1485. case 2:
  1486. startDate = "2010-01-01"
  1487. endDate = ""
  1488. case 3:
  1489. startDate = "2015-01-01"
  1490. endDate = ""
  1491. case 4:
  1492. //startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
  1493. startDate = "2021-01-01"
  1494. endDate = ""
  1495. case 5:
  1496. //startDate = startDate + "-01"
  1497. //endDate = endDate + "-01"
  1498. case 6:
  1499. //startDate = startDate + "-01"
  1500. endDate = ""
  1501. case 7:
  1502. startDate = "2018-01-01"
  1503. endDate = ""
  1504. case 8:
  1505. startDate = "2019-01-01"
  1506. endDate = ""
  1507. case 9:
  1508. startDate = "2020-01-01"
  1509. endDate = ""
  1510. case 11:
  1511. startDate = "2022-01-01"
  1512. endDate = ""
  1513. }
  1514. // 兼容日期错误
  1515. {
  1516. if strings.Count(startDate, "-") == 1 {
  1517. startDate = startDate + "-01"
  1518. }
  1519. if strings.Count(endDate, "-") == 1 {
  1520. endDate = endDate + "-01"
  1521. }
  1522. }
  1523. return
  1524. }
  1525. func GetDateByDateTypeV2(dateType int, tmpStartDate, tmpEndDate string, startYear, yearMax int) (startDate, endDate string) {
  1526. startDate = tmpStartDate
  1527. endDate = tmpEndDate
  1528. switch dateType {
  1529. case 1:
  1530. startDate = "2000-01-01"
  1531. endDate = ""
  1532. case 2:
  1533. startDate = "2010-01-01"
  1534. endDate = ""
  1535. case 3:
  1536. startDate = "2015-01-01"
  1537. endDate = ""
  1538. case 4:
  1539. //startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
  1540. startDate = "2021-01-01"
  1541. endDate = ""
  1542. case 5:
  1543. //startDate = startDate + "-01"
  1544. //endDate = endDate + "-01"
  1545. case 6:
  1546. //startDate = startDate + "-01"
  1547. endDate = ""
  1548. case 7:
  1549. startDate = "2018-01-01"
  1550. endDate = ""
  1551. case 8:
  1552. startDate = "2019-01-01"
  1553. endDate = ""
  1554. case 9:
  1555. startDate = "2020-01-01"
  1556. endDate = ""
  1557. case 11:
  1558. startDate = "2022-01-01"
  1559. endDate = ""
  1560. case DateTypeNYears:
  1561. if startYear == 0 { //默认取最近5年
  1562. startYear = 5
  1563. }
  1564. if yearMax == 0 {
  1565. return
  1566. }
  1567. startYear = startYear - 1
  1568. baseDate, _ := time.Parse(FormatDate, fmt.Sprintf("%d-01-01", yearMax))
  1569. startDate = baseDate.AddDate(-startYear, 0, 0).Format(FormatDate)
  1570. endDate = ""
  1571. }
  1572. // 兼容日期错误
  1573. {
  1574. if strings.Count(startDate, "-") == 1 {
  1575. startDate = startDate + "-01"
  1576. }
  1577. if strings.Count(endDate, "-") == 1 {
  1578. endDate = endDate + "-01"
  1579. }
  1580. }
  1581. return
  1582. }
  1583. func TimeTransferString(format string, t time.Time) string {
  1584. str := t.Format(format)
  1585. if t.IsZero() {
  1586. return ""
  1587. }
  1588. return str
  1589. }
  1590. // GetDateByDateType2 通过dateType获取需要的开始/结束日期(日期类型:1:最近3月;2:最近6月;3:最近1年;4:最近2年;5:最近3年;6:最近5年;7:最近10年,8:自定义时间)
  1591. func GetDateByDateType2(dateType int, currDate time.Time) (startDate time.Time) {
  1592. switch dateType {
  1593. case 1:
  1594. startDate = currDate.AddDate(0, -3, 0)
  1595. case 2:
  1596. startDate = currDate.AddDate(0, -6, 0)
  1597. case 3:
  1598. startDate = currDate.AddDate(-1, 0, 0)
  1599. case 4:
  1600. startDate = currDate.AddDate(-2, 0, 0)
  1601. case 5:
  1602. startDate = currDate.AddDate(-3, 0, 0)
  1603. case 6:
  1604. startDate = currDate.AddDate(-5, 0, 0)
  1605. case 7:
  1606. startDate = currDate.AddDate(-10, 0, 0)
  1607. }
  1608. return
  1609. }
  1610. // GetCeilNewNum 保留n位有效数字的向上取整
  1611. // @params num 实际数据
  1612. // @params baseLen 需要保留的有效位数
  1613. func GetCeilNewNum(num float64, baseLen int) (newNum float64) {
  1614. if num >= 1 {
  1615. tmpNum := int(math.Ceil(num)) // 向上取整
  1616. str := strconv.Itoa(tmpNum)
  1617. lenStr := len(str)
  1618. if lenStr > baseLen {
  1619. newNumStr := str[0:baseLen]
  1620. newNumInt, _ := strconv.Atoi(newNumStr)
  1621. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1622. if newNum < num {
  1623. newNumInt += 1
  1624. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1625. }
  1626. } else {
  1627. newNum = float64(tmpNum)
  1628. }
  1629. return
  1630. } else if num > 0 {
  1631. // 这是小数
  1632. str := strconv.FormatFloat(num, 'f', -1, 64)
  1633. // 去除小数点和负号
  1634. str = removeDecimalPoint(str)
  1635. // 计算字符串长度
  1636. lenStr := len(str)
  1637. if lenStr > baseLen {
  1638. newNumStr := str[0:baseLen]
  1639. newNumInt, _ := strconv.Atoi(newNumStr)
  1640. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1641. if newNum < num {
  1642. newNumInt += 1
  1643. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1644. }
  1645. } else {
  1646. newNum = num
  1647. }
  1648. } else if num > -1 {
  1649. // 这是小数
  1650. str := strconv.FormatFloat(num, 'f', -1, 64)
  1651. // 去除小数点和负号
  1652. str = removeDecimalPoint(str)
  1653. // 计算字符串长度
  1654. lenStr := len(str)
  1655. if lenStr > baseLen {
  1656. newNumStr := str[0:baseLen]
  1657. newNumInt, _ := strconv.Atoi(newNumStr)
  1658. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1659. newNum = -newNum
  1660. if newNum < num {
  1661. newNumInt -= 1
  1662. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1663. newNum = -newNum
  1664. }
  1665. } else {
  1666. newNum = num
  1667. }
  1668. if newNum == -0 {
  1669. newNum = 0
  1670. }
  1671. } else { // 小于等于-1
  1672. tmpNumFloat := math.Abs(num)
  1673. tmpNum := int(math.Floor(tmpNumFloat)) // 向上取整
  1674. str := strconv.Itoa(tmpNum)
  1675. lenStr := len(str)
  1676. if lenStr > baseLen {
  1677. newNumStr := str[0:baseLen]
  1678. //fmt.Println("newNumStr:", newNumStr)
  1679. newNumInt, _ := strconv.Atoi(newNumStr)
  1680. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1681. newNum = -newNum
  1682. if newNum < num {
  1683. newNumInt -= 1
  1684. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1685. newNum = -newNum
  1686. }
  1687. } else {
  1688. newNum = float64(-tmpNum)
  1689. }
  1690. }
  1691. return
  1692. }
  1693. // GetFloorNewNum 保留n位有效数字的向下取整
  1694. // @params num 实际数据
  1695. // @params baseLen 需要保留的有效位数
  1696. func GetFloorNewNum(num float64, baseLen int) (newNum float64) {
  1697. if num >= 1 {
  1698. tmpNum := int(math.Floor(num)) // 向上取整
  1699. str := strconv.Itoa(tmpNum)
  1700. lenStr := len(str)
  1701. if lenStr > baseLen {
  1702. newNumStr := str[0:baseLen]
  1703. newNumInt, _ := strconv.Atoi(newNumStr)
  1704. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1705. if newNum < num {
  1706. newNumInt -= 1
  1707. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1708. }
  1709. } else {
  1710. newNum = float64(tmpNum)
  1711. }
  1712. return
  1713. } else if num > 0 {
  1714. // 这是小数
  1715. str := strconv.FormatFloat(num, 'f', -1, 64)
  1716. // 去除小数点和负号
  1717. str = removeDecimalPoint(str)
  1718. // 计算字符串长度
  1719. lenStr := len(str)
  1720. if lenStr > baseLen {
  1721. newNumStr := str[0:baseLen]
  1722. newNumInt, _ := strconv.Atoi(newNumStr)
  1723. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1724. if newNum > num {
  1725. newNumInt -= 1
  1726. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1727. }
  1728. } else {
  1729. newNum = num
  1730. }
  1731. } else if num > -1 {
  1732. // 这是小数
  1733. str := strconv.FormatFloat(num, 'f', -1, 64)
  1734. // 去除小数点和负号
  1735. str = removeDecimalPoint(str)
  1736. // 计算字符串长度
  1737. lenStr := len(str)
  1738. if lenStr > baseLen {
  1739. newNumStr := str[0:baseLen]
  1740. newNumInt, _ := strconv.Atoi(newNumStr)
  1741. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1742. newNum = -newNum
  1743. if newNum > num {
  1744. newNumInt += 1
  1745. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1746. newNum = -newNum
  1747. }
  1748. } else {
  1749. newNum = num
  1750. }
  1751. if newNum == -0 {
  1752. newNum = 0
  1753. }
  1754. } else { // 小于等于-1
  1755. tmpNumFloat := math.Abs(num)
  1756. tmpNum := int(math.Ceil(tmpNumFloat)) // 向上取整
  1757. str := strconv.Itoa(tmpNum)
  1758. lenStr := len(str)
  1759. if lenStr > baseLen {
  1760. newNumStr := str[0:baseLen]
  1761. //fmt.Println("newNumStr:", newNumStr)
  1762. newNumInt, _ := strconv.Atoi(newNumStr)
  1763. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1764. newNum = -newNum
  1765. if newNum > num {
  1766. newNumInt += 1
  1767. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1768. newNum = -newNum
  1769. }
  1770. } else {
  1771. newNum = float64(-tmpNum)
  1772. }
  1773. }
  1774. return
  1775. }
  1776. // 去除小数点和负号
  1777. func removeDecimalPoint(str string) string {
  1778. // 去除小数点
  1779. str = str[strings.Index(str, ".")+1:]
  1780. return str
  1781. }
  1782. // GetPredictEdbDayListByEndDate 根据截止日期获取预测指标日期列表
  1783. func GetPredictEdbDayListByEndDate(startDate, endDate time.Time, frequency string) (dayList []time.Time) {
  1784. //if !utils.InArrayByStr([]string{"日度", "周度", "月度"}, frequency)
  1785. switch frequency {
  1786. case "日度":
  1787. for currDate := startDate.AddDate(0, 0, 1); currDate.Before(endDate) || currDate.Equal(endDate); currDate = currDate.AddDate(0, 0, 1) {
  1788. //周六、日排除
  1789. if currDate.Weekday() == time.Sunday || currDate.Weekday() == time.Saturday {
  1790. continue
  1791. }
  1792. dayList = append(dayList, currDate)
  1793. }
  1794. case "周度":
  1795. //nextDate := startDate.AddDate(0, 0, 7)
  1796. for currDate := startDate.AddDate(0, 0, 7); currDate.Before(endDate) || currDate.Equal(endDate); currDate = currDate.AddDate(0, 0, 7) {
  1797. dayList = append(dayList, currDate)
  1798. }
  1799. case "旬度":
  1800. for currDate := startDate.AddDate(0, 0, 1); currDate.Before(endDate) || currDate.Equal(endDate); {
  1801. nextDate := currDate.AddDate(0, 0, 1)
  1802. //每个月的10号、20号、最后一天,那么就写入
  1803. if nextDate.Day() == 11 || nextDate.Day() == 21 || nextDate.Day() == 1 {
  1804. dayList = append(dayList, currDate)
  1805. }
  1806. currDate = nextDate
  1807. }
  1808. case "月度":
  1809. for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
  1810. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1811. if !currDate.After(endDate) && !currDate.Equal(startDate) {
  1812. dayList = append(dayList, currDate)
  1813. }
  1814. currDate = currDate.AddDate(0, 0, 1)
  1815. }
  1816. case "季度":
  1817. for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
  1818. // 每月的最后一天
  1819. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1820. if !currDate.After(endDate) && !currDate.Equal(startDate) {
  1821. // 季度日期就写入,否则不写入
  1822. if currDate.Month() == 3 || currDate.Month() == 6 || currDate.Month() == 9 || currDate.Month() == 12 {
  1823. dayList = append(dayList, currDate)
  1824. }
  1825. }
  1826. currDate = currDate.AddDate(0, 0, 1)
  1827. }
  1828. case "半年度":
  1829. for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
  1830. // 每月的最后一天
  1831. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1832. if !currDate.After(endDate) && !currDate.Equal(startDate) {
  1833. // 半年度日期就写入,否则不写入
  1834. if currDate.Month() == 6 || currDate.Month() == 12 {
  1835. dayList = append(dayList, currDate)
  1836. }
  1837. }
  1838. currDate = currDate.AddDate(0, 0, 1)
  1839. }
  1840. case "年度":
  1841. for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
  1842. currDate = time.Date(currDate.Year()+1, 12, 31, 0, 0, 0, 0, time.Now().Location())
  1843. if !currDate.After(endDate) && !currDate.Equal(startDate) {
  1844. dayList = append(dayList, currDate)
  1845. }
  1846. }
  1847. }
  1848. return
  1849. }
  1850. // GetPredictEdbDayListByNum 根据期数获取预测指标日期列表
  1851. func GetPredictEdbDayListByNum(startDate time.Time, num int, frequency string) (dayList []time.Time) {
  1852. switch frequency {
  1853. case "日度":
  1854. for i := 1; i <= num; {
  1855. currDate := startDate.AddDate(0, 0, i)
  1856. //周六、日排除
  1857. if currDate.Weekday() == time.Sunday || currDate.Weekday() == time.Saturday {
  1858. continue
  1859. }
  1860. dayList = append(dayList, currDate)
  1861. i++
  1862. }
  1863. case "周度":
  1864. for i := 1; i <= num; {
  1865. dayList = append(dayList, startDate.AddDate(0, 0, i*7))
  1866. i++
  1867. }
  1868. case "旬度":
  1869. currDate := startDate
  1870. for i := 1; i <= num; {
  1871. nextDate := currDate.AddDate(0, 0, 1)
  1872. //每个月的10号、20号、最后一天,那么就写入
  1873. if nextDate.Day() == 11 || nextDate.Day() == 21 || nextDate.Day() == 1 {
  1874. dayList = append(dayList, currDate)
  1875. i++
  1876. }
  1877. currDate = nextDate
  1878. }
  1879. case "月度":
  1880. currDate := startDate
  1881. for i := 1; i <= num; {
  1882. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1883. if !currDate.Equal(startDate) {
  1884. dayList = append(dayList, currDate)
  1885. i++
  1886. }
  1887. currDate = currDate.AddDate(0, 0, 1)
  1888. }
  1889. case "季度":
  1890. currDate := startDate
  1891. for i := 1; i <= num; {
  1892. // 每月的最后一天
  1893. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1894. if !currDate.Equal(startDate) {
  1895. // 季度日期就写入,否则不写入
  1896. if currDate.Month() == 3 || currDate.Month() == 6 || currDate.Month() == 9 || currDate.Month() == 12 {
  1897. dayList = append(dayList, currDate)
  1898. i++
  1899. }
  1900. }
  1901. currDate = currDate.AddDate(0, 0, 1)
  1902. }
  1903. case "半年度":
  1904. currDate := startDate
  1905. for i := 1; i <= num; {
  1906. // 每月的最后一天
  1907. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1908. if !currDate.Equal(startDate) {
  1909. // 半年度日期就写入,否则不写入
  1910. if currDate.Month() == 6 || currDate.Month() == 12 {
  1911. dayList = append(dayList, currDate)
  1912. i++
  1913. }
  1914. }
  1915. currDate = currDate.AddDate(0, 0, 1)
  1916. }
  1917. case "年度":
  1918. currDate := startDate
  1919. for i := 1; i <= num; {
  1920. currDate = time.Date(currDate.Year()+1, 12, 31, 0, 0, 0, 0, time.Now().Location())
  1921. if !currDate.Equal(startDate) {
  1922. dayList = append(dayList, currDate)
  1923. i++
  1924. }
  1925. }
  1926. }
  1927. return
  1928. }
  1929. // FormatMixTableDataShowValue 格式化自定表格显示数据
  1930. func FormatMixTableDataShowValue(x float64) (res string) {
  1931. res = strconv.FormatFloat(x, 'f', -1, 64)
  1932. return
  1933. }
  1934. // FormatTableDataShowValue 格式化自定表格显示数据
  1935. func FormatTableDataShowValue(x float64) (res string) {
  1936. if x > 1 || x < -1 {
  1937. res = decimal.NewFromFloat(x).Round(2).String()
  1938. return
  1939. }
  1940. // 介于-1到1之间
  1941. xStr := strconv.FormatFloat(x, 'f', -10, 64)
  1942. // 使用 strings.Split 函数将小数拆分为整数部分和小数部分
  1943. xParts := strings.Split(xStr, ".")
  1944. if len(xParts) < 2 {
  1945. res = fmt.Sprint(x)
  1946. return
  1947. }
  1948. // 计算小数部分的长度,即小数点后面的位数
  1949. xDecimals := len(xParts[1])
  1950. if xDecimals > 2 {
  1951. parts := xParts[1]
  1952. // 小数点后小于等于两位, 直接拼接返回
  1953. partLen := len(xParts[1])
  1954. if partLen <= 2 {
  1955. res = xParts[0] + "." + parts
  1956. return
  1957. }
  1958. // 找出第一个有效数字, 算出n
  1959. one := 0
  1960. for k, p := range parts {
  1961. // 48->0
  1962. if p != 48 {
  1963. if one == 0 {
  1964. one = k + 1
  1965. }
  1966. }
  1967. }
  1968. n := partLen - one
  1969. if n >= 1 {
  1970. n -= 1
  1971. } else {
  1972. one -= 1
  1973. }
  1974. var partFloat float64
  1975. partInt, _ := strconv.Atoi(parts)
  1976. partFloat, _ = decimal.NewFromInt(int64(partInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(n)))).Float64()
  1977. partFloat = math.Round(partFloat)
  1978. partFloat, _ = decimal.NewFromFloat(partFloat).Div(decimal.NewFromFloat(math.Pow(10, float64(one+1)))).Float64()
  1979. resParts := strings.Split(fmt.Sprint(partFloat), ".")
  1980. resPart := ""
  1981. if len(resParts) > 1 {
  1982. resPart = resParts[1]
  1983. } else {
  1984. resPart = resParts[0]
  1985. }
  1986. res = xParts[0] + "." + resPart
  1987. }
  1988. if xDecimals <= 2 {
  1989. xDecimalsStr := xParts[1]
  1990. x, _ = strconv.ParseFloat(xParts[0]+"."+xDecimalsStr, 64)
  1991. res = xParts[0] + "." + xDecimalsStr
  1992. }
  1993. return
  1994. }
  1995. func DealDateTimeZero(t time.Time, format string) (timeStr string) {
  1996. if !t.IsZero() {
  1997. timeStr = t.Format(format)
  1998. }
  1999. return
  2000. }
  2001. // IsPercentage
  2002. // @Description: 判断一个字符串是否是百分比的字符串,并返回百分比的值(比如:50%,返回true 50)
  2003. // @author: Roc
  2004. // @datetime 2023-11-29 14:00:31
  2005. // @param input string
  2006. // @return bool
  2007. // @return string
  2008. func IsPercentage(input string) (bool, string) {
  2009. percentagePattern := `^-?(\d+(\.\d+)?)%$`
  2010. match, _ := regexp.MatchString(percentagePattern, input)
  2011. if match {
  2012. re := regexp.MustCompile(percentagePattern)
  2013. match := re.FindStringSubmatch(input)
  2014. // 区分负数和正数,确保返回结果包含负号(如有)
  2015. sign := "-"
  2016. if input[0] != '-' {
  2017. sign = ""
  2018. }
  2019. return true, sign + match[1]
  2020. }
  2021. return false, ""
  2022. }
  2023. // GetLikeKeyword
  2024. //
  2025. // @Description: 获取sql查询中的like查询字段
  2026. // @author: Roc
  2027. // @datetime2023-10-23 14:46:32
  2028. // @param keyword string
  2029. // @return string
  2030. func GetLikeKeyword(keyword string) string {
  2031. return `%` + keyword + `%`
  2032. }
  2033. // GetLikeKeywordPars
  2034. //
  2035. // @Description: 获取sql查询中的参数切片
  2036. // @author: Roc
  2037. // @datetime2023-10-23 14:50:18
  2038. // @param pars []interface{}
  2039. // @param keyword string
  2040. // @param num int
  2041. // @return newPars []interface{}
  2042. func GetLikeKeywordPars(pars []interface{}, keyword string, num int) (newPars []interface{}) {
  2043. newPars = pars
  2044. if newPars == nil {
  2045. newPars = make([]interface{}, 0)
  2046. }
  2047. for i := 1; i <= num; i++ {
  2048. newPars = append(newPars, `%`+keyword+`%`)
  2049. }
  2050. return
  2051. }
  2052. func GetSign(nonce, timestamp, appId, secret string) (sign string) {
  2053. signStrMap := map[string]string{
  2054. "nonce": nonce,
  2055. "timestamp": timestamp,
  2056. "appid": appId,
  2057. }
  2058. keys := make([]string, 0, len(signStrMap))
  2059. for k := range signStrMap {
  2060. keys = append(keys, k)
  2061. }
  2062. sort.Strings(keys)
  2063. var signStr string
  2064. for _, k := range keys {
  2065. signStr += k + "=" + signStrMap[k] + "&"
  2066. }
  2067. signStr = strings.Trim(signStr, "&")
  2068. fmt.Println("signStr:" + signStr)
  2069. sign = HmacSha256ToBase64(secret, signStr)
  2070. return
  2071. }
  2072. // HmacSha256ToBase64 将加密后的二进制转Base64字符串
  2073. func HmacSha256ToBase64(key string, data string) string {
  2074. return base64.URLEncoding.EncodeToString(HmacSha256(key, data))
  2075. }
  2076. // HmacSha256 计算HmacSha256
  2077. // key 是加密所使用的key
  2078. // data 是加密的内容
  2079. func HmacSha256(key string, data string) []byte {
  2080. mac := hmac.New(sha256.New, []byte(key))
  2081. _, _ = mac.Write([]byte(data))
  2082. return mac.Sum(nil)
  2083. }
  2084. func PascalToSnake(s string) string {
  2085. var result []rune
  2086. for i, char := range s {
  2087. // 在大写字母前插入下划线,除非是第一个字母
  2088. if i > 0 && unicode.IsUpper(char) {
  2089. result = append(result, '_')
  2090. }
  2091. // 将字母转为小写
  2092. result = append(result, unicode.ToLower(char))
  2093. }
  2094. return string(result)
  2095. }
  2096. // ArrContainsStr函数检查一个字符串是否在字符串数组中
  2097. func ArrContainsStr(arr []string, str string) bool {
  2098. for _, v := range arr {
  2099. if v == str {
  2100. return true
  2101. }
  2102. }
  2103. return false
  2104. }
  2105. func GetColorMap() map[int]string {
  2106. colorMap := make(map[int]string)
  2107. colors := []string{"#0000FF", "#FF0000", "#999999", "#000000", "#7CB5EC", "#90ED7D", "#F7A35C", "#8085E9",
  2108. "#F15C80", "#E4D354", "#2B908F", "#F45B5B", "#91E8E1", "#FDA8C7", "#8A4294",
  2109. "#578B5A", "#0033FF", "#849EC1", "#FFDF0C", "#005496", "#00F0FF", "#4D535B",
  2110. "#4F4C34", "#804141", "#86BABD", "#8AA3FF", "#960000", "#A173DB", "#A39340",
  2111. "#CE814A", "#D1D2E6", "#EAB7B7", "#FF2E7A", "#FF4AF8", "#FF785B", "#FF9696", "#FFA800", "#FFBC97", "#FFDFDF"}
  2112. for k, v := range colors {
  2113. colorMap[k] = v
  2114. }
  2115. return colorMap
  2116. }
  2117. // 检查src属性是否以http或data:image开头
  2118. func isValidSrc(src string) bool {
  2119. // 使用Parse函数解析URL
  2120. parsedURL, err := url.Parse(src)
  2121. if err != nil {
  2122. validSchemes := regexp.MustCompile(`^data:image\/.*;base64,.*$`)
  2123. return validSchemes.MatchString(src)
  2124. }
  2125. if parsedURL.Host == "" || (parsedURL.Scheme != "http" && parsedURL.Scheme != "https") {
  2126. validSchemes := regexp.MustCompile(`^data:image\/.*;base64,.*$`)
  2127. return validSchemes.MatchString(src)
  2128. }
  2129. return true
  2130. }
  2131. // ContentXssCheck 校验文本中的JS代码
  2132. func ContentXssCheck(content string) (err error) {
  2133. // 解析HTML内容
  2134. node, err := xhtml.Parse(strings.NewReader(content))
  2135. if err != nil {
  2136. err = fmt.Errorf(" html.Parse Err: %v", err)
  2137. return
  2138. }
  2139. // 遍历解析后的节点树,查找特定标签
  2140. var visit func(n *xhtml.Node) error
  2141. visit = func(n *xhtml.Node) error {
  2142. if n.Type == xhtml.ElementNode {
  2143. lowerData := strings.ToLower(n.Data)
  2144. switch lowerData {
  2145. case "script", "javascript":
  2146. err = fmt.Errorf(" script is forbidden")
  2147. return err
  2148. default:
  2149. for _, attr := range n.Attr { //判断事件
  2150. lowerKey := strings.ToLower(attr.Key)
  2151. lowerVal := strings.ToLower(attr.Val)
  2152. if lowerKey == "src" || lowerKey == "dynsrc" || lowerKey == "background" || lowerKey == "lowsrc" {
  2153. if lowerVal != `` && !isValidSrc(lowerVal) {
  2154. err = fmt.Errorf("invalid src attribute value: %s", attr.Val)
  2155. return err
  2156. }
  2157. }
  2158. if strings.HasPrefix(lowerKey, "on") {
  2159. err = fmt.Errorf("the event is forbidden: %s:%s", attr.Key, attr.Val)
  2160. return err
  2161. }
  2162. if lowerKey == "style" {
  2163. if strings.Contains(lowerVal, "javascript:") || strings.Contains(lowerVal, "script:") {
  2164. err = fmt.Errorf("invalid style attribute value: %s", attr.Val)
  2165. return err
  2166. }
  2167. }
  2168. }
  2169. /* case "src":
  2170. // 如果<src>是某个标签的属性,你可能需要递归检查其父节点
  2171. // 这里简单起见,我们假设<src>不是有效的HTML标签,并忽略它
  2172. // 在实际中,你可能需要更复杂的逻辑来处理这种情况
  2173. fmt.Println("Warning: Unexpected 'src' tag found.")*/
  2174. }
  2175. }
  2176. for c := n.FirstChild; c != nil; c = c.NextSibling {
  2177. if err = visit(c); err != nil {
  2178. return err
  2179. }
  2180. }
  2181. return nil
  2182. }
  2183. // 检查HTML文档中的事件
  2184. if err = visit(node); err != nil {
  2185. return
  2186. }
  2187. return
  2188. }
  2189. func ContentXssFilter(content string) (cleanContent string) {
  2190. p := customXssPolicy()
  2191. // The policy can then be used to sanitize lots of input and it is safe to use the policy in multiple goroutines
  2192. cleanContent = p.Sanitize(
  2193. content,
  2194. )
  2195. return
  2196. }
  2197. func customXssPolicy() (p *bluemonday.Policy) {
  2198. p = bluemonday.UGCPolicy()
  2199. // iframe
  2200. p.AllowElements("iframe")
  2201. p.AllowAttrs("width").OnElements("iframe")
  2202. p.AllowAttrs("height").OnElements("iframe")
  2203. p.AllowAttrs("src").OnElements("iframe")
  2204. p.AllowAttrs("frameborder").Matching(bluemonday.Number).OnElements("iframe")
  2205. p.AllowAttrs("allow").Matching(regexp.MustCompile(`[a-z; -]*`)).OnElements("iframe")
  2206. p.AllowAttrs("allowfullscreen").OnElements("iframe")
  2207. return
  2208. }
  2209. // SecondsToHHMMSS 秒转HH:MM:SS
  2210. func SecondsToHHMMSS(seconds int) string {
  2211. duration := time.Duration(seconds) * time.Second
  2212. hours := int(duration.Hours())
  2213. minutes := int(duration.Minutes()) % 60
  2214. seconds = int(duration.Seconds()) % 60
  2215. if hours > 0 {
  2216. return fmt.Sprintf("%02d:%02d:%02d", hours, minutes, seconds)
  2217. } else {
  2218. return fmt.Sprintf("%02d:%02d", minutes, seconds)
  2219. }
  2220. }
  2221. // MillisecondsToHHMMSS 毫秒转HH:MM:SS
  2222. func MillisecondsToHHMMSS(ms int) string {
  2223. duration := time.Duration(ms) * time.Millisecond
  2224. hours := int(duration / (time.Hour))
  2225. minutes := int((duration % (time.Hour)) / time.Minute)
  2226. seconds := int((duration % time.Hour % time.Minute) / time.Second)
  2227. // 将整数小时、分钟和秒数转换为字符串,并添加冒号分隔符
  2228. hourStr := strconv.Itoa(hours)
  2229. minuteStr := strconv.Itoa(minutes)
  2230. secondStr := strconv.Itoa(seconds)
  2231. // 根据不足两位数的情况补零
  2232. if len(hourStr) == 1 {
  2233. hourStr = "0" + hourStr
  2234. }
  2235. if len(minuteStr) == 1 {
  2236. minuteStr = "0" + minuteStr
  2237. }
  2238. if len(secondStr) == 1 {
  2239. secondStr = "0" + secondStr
  2240. }
  2241. return hourStr + ":" + minuteStr + ":" + secondStr
  2242. }
  2243. func ByteToMB(byteCount int) float64 {
  2244. return float64(byteCount) / (1024 * 1024)
  2245. }
  2246. // DateConvMysqlConvMongo
  2247. // @Description: 将mysql中的日期比较符转换成mongo中的日期比较符
  2248. // @author: Roc
  2249. // @datetime 2024-05-08 11:03:26
  2250. // @param dateCon string
  2251. func DateConvMysqlConvMongo(dateCon string) string {
  2252. cond := ""
  2253. switch dateCon {
  2254. case "=":
  2255. cond = "$eq"
  2256. case "<":
  2257. cond = "$lt"
  2258. case "<=":
  2259. cond = "$lte"
  2260. case ">":
  2261. cond = "$gt"
  2262. case ">=":
  2263. cond = "$gte"
  2264. }
  2265. return cond
  2266. }
  2267. // handleSystemAppointDateT
  2268. // @Description: 处理系统日期相关的指定频率(所在周/旬/月/季/半年/年的最后/最早一天)
  2269. // @author: Roc
  2270. // @datetime2023-10-27 09:31:35
  2271. // @param Frequency string
  2272. // @param Day string
  2273. // @return date string
  2274. // @return err error
  2275. // @return errMsg string
  2276. func HandleSystemAppointDateT(currDate time.Time, appointDay, frequency string) (date string, err error, errMsg string) {
  2277. //currDate := time.Now()
  2278. switch frequency {
  2279. case "本周":
  2280. day := int(currDate.Weekday())
  2281. if day == 0 { // 周日
  2282. day = 7
  2283. }
  2284. num := 0
  2285. switch appointDay {
  2286. case "周一":
  2287. num = 1
  2288. case "周二":
  2289. num = 2
  2290. case "周三":
  2291. num = 3
  2292. case "周四":
  2293. num = 4
  2294. case "周五":
  2295. num = 5
  2296. case "周六":
  2297. num = 6
  2298. case "周日":
  2299. num = 7
  2300. }
  2301. day = num - day
  2302. date = currDate.AddDate(0, 0, day).Format(FormatDate)
  2303. case "本旬":
  2304. day := currDate.Day()
  2305. var tmpDate time.Time
  2306. switch appointDay {
  2307. case "第一天":
  2308. if day <= 10 {
  2309. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  2310. } else if day <= 20 {
  2311. tmpDate = time.Date(currDate.Year(), currDate.Month(), 11, 0, 0, 0, 0, currDate.Location())
  2312. } else {
  2313. tmpDate = time.Date(currDate.Year(), currDate.Month(), 21, 0, 0, 0, 0, currDate.Location())
  2314. }
  2315. case "最后一天":
  2316. if day <= 10 {
  2317. tmpDate = time.Date(currDate.Year(), currDate.Month(), 10, 0, 0, 0, 0, currDate.Location())
  2318. } else if day <= 20 {
  2319. tmpDate = time.Date(currDate.Year(), currDate.Month(), 20, 0, 0, 0, 0, currDate.Location())
  2320. } else {
  2321. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  2322. }
  2323. }
  2324. date = tmpDate.Format(FormatDate)
  2325. case "本月":
  2326. var tmpDate time.Time
  2327. switch appointDay {
  2328. case "第一天":
  2329. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  2330. case "最后一天":
  2331. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  2332. }
  2333. date = tmpDate.Format(FormatDate)
  2334. case "本季":
  2335. month := currDate.Month()
  2336. var tmpDate time.Time
  2337. switch appointDay {
  2338. case "第一天":
  2339. if month <= 3 {
  2340. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  2341. } else if month <= 6 {
  2342. tmpDate = time.Date(currDate.Year(), 4, 1, 0, 0, 0, 0, currDate.Location())
  2343. } else if month <= 9 {
  2344. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  2345. } else {
  2346. tmpDate = time.Date(currDate.Year(), 10, 1, 0, 0, 0, 0, currDate.Location())
  2347. }
  2348. case "最后一天":
  2349. if month <= 3 {
  2350. tmpDate = time.Date(currDate.Year(), 3, 31, 0, 0, 0, 0, currDate.Location())
  2351. } else if month <= 6 {
  2352. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  2353. } else if month <= 9 {
  2354. tmpDate = time.Date(currDate.Year(), 9, 30, 0, 0, 0, 0, currDate.Location())
  2355. } else {
  2356. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  2357. }
  2358. }
  2359. date = tmpDate.Format(FormatDate)
  2360. case "本半年":
  2361. month := currDate.Month()
  2362. var tmpDate time.Time
  2363. switch appointDay {
  2364. case "第一天":
  2365. if month <= 6 {
  2366. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  2367. } else {
  2368. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  2369. }
  2370. case "最后一天":
  2371. if month <= 6 {
  2372. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  2373. } else {
  2374. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  2375. }
  2376. }
  2377. date = tmpDate.Format(FormatDate)
  2378. case "本年":
  2379. var tmpDate time.Time
  2380. switch appointDay {
  2381. case "第一天":
  2382. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  2383. case "最后一天":
  2384. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  2385. }
  2386. date = tmpDate.Format(FormatDate)
  2387. default:
  2388. errMsg = "错误的日期频度:" + frequency
  2389. err = errors.New(errMsg)
  2390. return
  2391. }
  2392. return
  2393. }
  2394. func CompareFloatByOpStrings(op string, a, b float64) bool {
  2395. switch op {
  2396. case "=":
  2397. return a == b
  2398. case ">":
  2399. return a > b
  2400. case ">=":
  2401. return a >= b
  2402. case "<=":
  2403. return a <= b
  2404. case "<":
  2405. return a < b
  2406. }
  2407. return false
  2408. }
  2409. func GetDuration(filePath string) (duration string, err error) {
  2410. // 构建 FFmpeg 命令,使用 ffprobe 来获取媒体文件信息
  2411. cmd := exec.Command("ffprobe", "-i", filePath, "-show_entries", "format=duration", "-v", "quiet", "-of", "csv=p=0")
  2412. var out bytes.Buffer
  2413. cmd.Stdout = &out
  2414. // 执行命令并捕获输出
  2415. err = cmd.Run()
  2416. if err != nil {
  2417. return "", err
  2418. }
  2419. // 使用正则表达式匹配输出中的时长信息
  2420. re := regexp.MustCompile(`\d+\.\d+`)
  2421. duration = re.FindString(out.String())
  2422. return duration, nil
  2423. }