common.go 71 KB

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