common.go 78 KB

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