common.go 75 KB

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