common.go 59 KB

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