common.go 75 KB

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