common.go 65 KB

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