common.go 69 KB

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