common.go 56 KB

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