common.go 73 KB

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