common.go 74 KB

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