common.go 66 KB

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