common.go 75 KB

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