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