common.go 69 KB

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