common.go 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846
  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. "gorm.io/gorm"
  15. "html"
  16. "image"
  17. "image/png"
  18. "io"
  19. "math"
  20. "math/rand"
  21. "net"
  22. "net/http"
  23. "net/url"
  24. "os"
  25. "os/exec"
  26. "path"
  27. "reflect"
  28. "regexp"
  29. "sort"
  30. "strconv"
  31. "strings"
  32. "time"
  33. "unicode"
  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. // @return interface{}
  2557. // @return error
  2558. func ReflectSetField(original, result interface{}, fieldsToProcess []string) error {
  2559. // 通过反射处理时间字段
  2560. fieldsToProcess = []string{"CreateTime", "ModifyTime", "BaseModifyTime", "StartDate", "EndDate"}
  2561. for _, fieldName := range fieldsToProcess {
  2562. value := reflect.ValueOf(original).FieldByName(fieldName)
  2563. if !value.IsValid() {
  2564. continue
  2565. }
  2566. //fmt.Println("fieldName:", fieldName)
  2567. //fmt.Println(value.Kind())
  2568. //fmt.Println(value.Type())
  2569. //fmt.Println(reflect.TypeOf(time.Time{}) == value.Type())
  2570. // 如果是时间类型,那么就写入结果中
  2571. if reflect.TypeOf(time.Time{}) == value.Type() {
  2572. t := value.Interface().(time.Time)
  2573. tmpVal := ``
  2574. if t.IsZero() {
  2575. tmpVal = ``
  2576. } else {
  2577. tmpVal = t.Format(FormatDateTime)
  2578. }
  2579. v := reflect.ValueOf(result).Elem()
  2580. f := v.FieldByName(fieldName)
  2581. if !f.IsValid() {
  2582. fmt.Printf("Field '%s' not found in the struct.\n", fieldName)
  2583. continue
  2584. }
  2585. f.Set(reflect.ValueOf(tmpVal))
  2586. }
  2587. }
  2588. return nil
  2589. }