common.go 63 KB

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