common.go 74 KB

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