common.go 75 KB

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