common.go 77 KB

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