12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073 |
- package utils
- import (
- "crypto/hmac"
- "crypto/md5"
- "crypto/sha1"
- "crypto/sha256"
- "encoding/base64"
- "encoding/hex"
- "encoding/json"
- "fmt"
- "github.com/PuerkitoBio/goquery"
- "html"
- "image"
- "image/png"
- "math"
- "math/rand"
- "net"
- "os"
- "os/exec"
- "regexp"
- "sort"
- "strconv"
- "strings"
- "time"
- "unicode"
- "unicode/utf8"
- )
- // 随机数种子
- var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
- func GetRandString(size int) string {
- 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", "!", "@", "#", "$", "%", "^", "&", "*"}
- randomSb := ""
- digitSize := len(allLetterDigit)
- for i := 0; i < size; i++ {
- randomSb += allLetterDigit[rnd.Intn(digitSize)]
- }
- return randomSb
- }
- func GetRandStringNoSpecialChar(size int) string {
- 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"}
- randomSb := ""
- digitSize := len(allLetterDigit)
- for i := 0; i < size; i++ {
- randomSb += allLetterDigit[rnd.Intn(digitSize)]
- }
- return randomSb
- }
- func StringsToJSON(str string) string {
- rs := []rune(str)
- jsons := ""
- for _, r := range rs {
- rint := int(r)
- if rint < 128 {
- jsons += string(r)
- } else {
- jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
- }
- }
- return jsons
- }
- // 序列化
- func ToString(v interface{}) string {
- data, _ := json.Marshal(v)
- return string(data)
- }
- // md5加密
- func MD5(data string) string {
- m := md5.Sum([]byte(data))
- return hex.EncodeToString(m[:])
- }
- // md5加密
- func Get16MD5Encode(data string) string {
- m := md5.Sum([]byte(data))
- encodehex := hex.EncodeToString(m[:])
- return encodehex[8:24]
- }
- // 获取数字随机字符
- func GetRandDigit(n int) string {
- return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
- }
- // 获取随机数
- func GetRandNumber(n int) int {
- return rnd.Intn(n)
- }
- func GetRandInt(min, max int) int {
- if min >= max || min == 0 || max == 0 {
- return max
- }
- return rand.Intn(max-min) + min
- }
- func GetToday(format string) string {
- today := time.Now().Format(format)
- return today
- }
- // 获取今天剩余秒数
- func GetTodayLastSecond() time.Duration {
- today := GetToday(FormatDate) + " 23:59:59"
- end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
- return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
- }
- // 处理出生日期函数
- func GetBrithDate(idcard string) string {
- l := len(idcard)
- var s string
- if l == 15 {
- s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
- return s
- }
- if l == 18 {
- s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
- return s
- }
- return GetToday(FormatDate)
- }
- // 处理性别
- func WhichSexByIdcard(idcard string) string {
- var sexs = [2]string{"女", "男"}
- length := len(idcard)
- if length == 18 {
- sex, _ := strconv.Atoi(string(idcard[16]))
- return sexs[sex%2]
- } else if length == 15 {
- sex, _ := strconv.Atoi(string(idcard[14]))
- return sexs[sex%2]
- }
- return "男"
- }
- // 截取小数点后几位
- func SubFloatToString(f float64, m int) string {
- n := strconv.FormatFloat(f, 'f', -1, 64)
- if n == "" {
- return ""
- }
- if m >= len(n) {
- return n
- }
- newn := strings.Split(n, ".")
- if m == 0 {
- return newn[0]
- }
- if len(newn) < 2 || m >= len(newn[1]) {
- return n
- }
- return newn[0] + "." + newn[1][:m]
- }
- // 截取小数点后几位
- func SubFloatToFloat(f float64, m int) float64 {
- newn := SubFloatToString(f, m)
- newf, _ := strconv.ParseFloat(newn, 64)
- return newf
- }
- // 获取相差时间-年
- func GetYearDiffer(start_time, end_time string) int {
- t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
- t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
- age := t2.Year() - t1.Year()
- if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
- age--
- }
- return age
- }
- // 获取相差时间-秒
- func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
- diff := end_time.Unix() - start_time.Unix()
- return diff
- }
- func FixFloat(f float64, m int) float64 {
- newn := SubFloatToString(f+0.00000001, m)
- newf, _ := strconv.ParseFloat(newn, 64)
- return newf
- }
- // 将字符串数组转化为逗号分割的字符串形式 ["str1","str2","str3"] >>> "str1,str2,str3"
- func StrListToString(strList []string) (str string) {
- if len(strList) > 0 {
- for k, v := range strList {
- if k == 0 {
- str = v
- } else {
- str = str + "," + v
- }
- }
- return
- }
- return ""
- }
- // Token
- func GetToken() string {
- randStr := GetRandString(64)
- token := MD5(randStr + Md5Key)
- tokenLen := 64 - len(token)
- return strings.ToUpper(token + GetRandString(tokenLen))
- }
- // 数据没有记录
- func ErrNoRow() string {
- return "<QuerySeter> no row found"
- }
- // 校验邮箱格式
- func ValidateEmailFormatat(email string) bool {
- reg := regexp.MustCompile(RegularEmail)
- return reg.MatchString(email)
- }
- // 验证是否是手机号
- func ValidateMobileFormatat(mobileNum string) bool {
- reg := regexp.MustCompile(RegularMobile)
- return reg.MatchString(mobileNum)
- }
- // 验证是否是固定电话
- func ValidateFixedTelephoneFormatat(mobileNum string) bool {
- reg := regexp.MustCompile(RegularFixedTelephone)
- return reg.MatchString(mobileNum)
- }
- // 验证是否是固定电话宽松
- func ValidateFixedTelephoneFormatatEasy(mobileNum string) bool {
- reg := regexp.MustCompile(RegularFixedTelephoneEasy)
- return reg.MatchString(mobileNum)
- }
- // 判断文件是否存在
- func FileIsExist(filePath string) bool {
- _, err := os.Stat(filePath)
- return err == nil || os.IsExist(err)
- }
- // 获取图片扩展名
- func GetImgExt(file string) (ext string, err error) {
- var headerByte []byte
- headerByte = make([]byte, 8)
- fd, err := os.Open(file)
- if err != nil {
- return "", err
- }
- defer fd.Close()
- _, err = fd.Read(headerByte)
- if err != nil {
- return "", err
- }
- xStr := fmt.Sprintf("%x", headerByte)
- switch {
- case xStr == "89504e470d0a1a0a":
- ext = ".png"
- case xStr == "0000010001002020":
- ext = ".ico"
- case xStr == "0000020001002020":
- ext = ".cur"
- case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
- ext = ".gif"
- case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
- ext = ".tga"
- case xStr[:8] == "464f524d":
- ext = ".iff"
- case xStr[:8] == "52494646":
- ext = ".ani"
- case xStr[:4] == "4d4d" || xStr[:4] == "4949":
- ext = ".tiff"
- case xStr[:4] == "424d":
- ext = ".bmp"
- case xStr[:4] == "ffd8":
- ext = ".jpg"
- case xStr[:2] == "0a":
- ext = ".pcx"
- default:
- ext = ""
- }
- return ext, nil
- }
- // 保存图片
- func SaveImage(path string, img image.Image) (err error) {
- //需要保持的文件
- imgfile, err := os.Create(path)
- defer imgfile.Close()
- // 以PNG格式保存文件
- err = png.Encode(imgfile, img)
- return err
- }
- // 保存base64数据为文件
- func SaveBase64ToFile(content, path string) error {
- data, err := base64.StdEncoding.DecodeString(content)
- if err != nil {
- return err
- }
- f, err := os.Create(path)
- defer f.Close()
- if err != nil {
- return err
- }
- f.Write(data)
- return nil
- }
- func SaveBase64ToFileBySeek(content, path string) (err error) {
- data, err := base64.StdEncoding.DecodeString(content)
- exist, err := PathExists(path)
- if err != nil {
- return
- }
- if !exist {
- f, err := os.Create(path)
- if err != nil {
- return err
- }
- n, _ := f.Seek(0, 2)
- // 从末尾的偏移量开始写入内容
- _, err = f.WriteAt([]byte(data), n)
- defer f.Close()
- } else {
- f, err := os.OpenFile(path, os.O_WRONLY, 0644)
- if err != nil {
- return err
- }
- n, _ := f.Seek(0, 2)
- // 从末尾的偏移量开始写入内容
- _, err = f.WriteAt([]byte(data), n)
- defer f.Close()
- }
- return nil
- }
- func PathExists(path string) (bool, error) {
- _, err := os.Stat(path)
- if err == nil {
- return true, nil
- }
- if os.IsNotExist(err) {
- return false, nil
- }
- return false, err
- }
- func StartIndex(page, pagesize int) int {
- if page > 1 {
- return (page - 1) * pagesize
- }
- return 0
- }
- func PageCount(count, pagesize int) int {
- if count%pagesize > 0 {
- return count/pagesize + 1
- } else {
- return count / pagesize
- }
- }
- func TrimHtml(src string) string {
- //将HTML标签全转换成小写
- re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
- src = re.ReplaceAllStringFunc(src, strings.ToLower)
- re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
- src = re.ReplaceAllString(src, "[图片]")
- re, _ = regexp.Compile("class[\\S\\s]+?>")
- src = re.ReplaceAllString(src, "")
- re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
- src = re.ReplaceAllString(src, "")
- return strings.TrimSpace(src)
- }
- //1556164246 -> 2019-04-25 03:50:46 +0000
- //timestamp
- func TimeToTimestamp() {
- fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
- }
- func ToUnicode(text string) string {
- textQuoted := strconv.QuoteToASCII(text)
- textUnquoted := textQuoted[1 : len(textQuoted)-1]
- return textUnquoted
- }
- func VersionToInt(version string) int {
- version = strings.Replace(version, ".", "", -1)
- n, _ := strconv.Atoi(version)
- return n
- }
- func IsCheckInList(list []int, s int) bool {
- for _, v := range list {
- if v == s {
- return true
- }
- }
- return false
- }
- func round(num float64) int {
- return int(num + math.Copysign(0.5, num))
- }
- func toFixed(num float64, precision int) float64 {
- output := math.Pow(10, float64(precision))
- return float64(round(num*output)) / output
- }
- // GetWilsonScore returns Wilson Score
- func GetWilsonScore(p, n float64) float64 {
- if p == 0 && n == 0 {
- return 0
- }
- 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)
- }
- // 将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
- func ChangeWordsToNum(str string) (numStr string) {
- words := ([]rune)(str)
- num := 0
- n := 0
- for i := 0; i < len(words); i++ {
- word := string(words[i : i+1])
- switch word {
- case "万":
- if n == 0 {
- n = 1
- }
- n = n * 10000
- num = num*10000 + n
- n = 0
- case "千":
- if n == 0 {
- n = 1
- }
- n = n * 1000
- num += n
- n = 0
- case "百":
- if n == 0 {
- n = 1
- }
- n = n * 100
- num += n
- n = 0
- case "十":
- if n == 0 {
- n = 1
- }
- n = n * 10
- num += n
- n = 0
- case "一":
- n += 1
- case "二":
- n += 2
- case "三":
- n += 3
- case "四":
- n += 4
- case "五":
- n += 5
- case "六":
- n += 6
- case "七":
- n += 7
- case "八":
- n += 8
- case "九":
- n += 9
- case "零":
- default:
- if n > 0 {
- num += n
- n = 0
- }
- if num == 0 {
- numStr += word
- } else {
- numStr += strconv.Itoa(num) + word
- num = 0
- }
- }
- }
- if n > 0 {
- num += n
- n = 0
- }
- if num != 0 {
- numStr += strconv.Itoa(num)
- }
- return
- }
- func Sha1(data string) string {
- sha1 := sha1.New()
- sha1.Write([]byte(data))
- return hex.EncodeToString(sha1.Sum([]byte("")))
- }
- func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
- cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
- out, err := exec.Command("bash", "-c", cmd).Output()
- if err != nil {
- return
- }
- outTimes := string(out)
- fmt.Println("outTimes:", outTimes)
- if outTimes != "" {
- timeArr := strings.Split(outTimes, ":")
- h := timeArr[0]
- m := timeArr[1]
- s := timeArr[2]
- hInt, err := strconv.Atoi(h)
- if err != nil {
- return playSeconds, err
- }
- mInt, err := strconv.Atoi(m)
- if err != nil {
- return playSeconds, err
- }
- s = strings.Trim(s, " ")
- s = strings.Trim(s, "\n")
- sInt, err := strconv.ParseFloat(s, 64)
- if err != nil {
- return playSeconds, err
- }
- playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
- }
- return
- }
- func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
- tradeCode = strings.Replace(tradeCode, "W", "", -1)
- tradeCode = strings.Trim(tradeCode, " ")
- tradeCodeInt, err := strconv.Atoi(tradeCode)
- if err != nil {
- return
- }
- tradeCodeInt = tradeCodeInt + 1
- maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
- return
- }
- // excel日期字段格式化 yyyy-mm-dd
- func ConvertToFormatDay(excelDaysString string) string {
- // 2006-01-02 距离 1900-01-01的天数
- baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
- curDiffDay := excelDaysString
- b, _ := strconv.Atoi(curDiffDay)
- // 获取excel的日期距离2006-01-02的天数
- realDiffDay := b - baseDiffDay
- //fmt.Println("realDiffDay:",realDiffDay)
- // 距离2006-01-02 秒数
- realDiffSecond := realDiffDay * 24 * 3600
- //fmt.Println("realDiffSecond:",realDiffSecond)
- // 2006-01-02 15:04:05距离1970-01-01 08:00:00的秒数 网上工具可查出
- baseOriginSecond := 1136185445
- resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
- return resultTime
- }
- // 字符串转换为time
- func StrTimeToTime(strTime string) time.Time {
- timeLayout := "2006-01-02 15:04:05" //转化所需模板
- loc, _ := time.LoadLocation("Local") //重要:获取时区
- resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
- return resultTime
- }
- // 时间格式去掉时分秒
- func TimeRemoveHms(strTime string) string {
- var Ymd string
- var resultTime = StrTimeToTime(strTime)
- year := resultTime.Year()
- month := resultTime.Format("01")
- day1 := resultTime.Day()
- if day1 < 10 {
- Ymd = strconv.Itoa(year) + "." + month + ".0" + strconv.Itoa(day1)
- } else {
- Ymd = strconv.Itoa(year) + "." + month + "." + strconv.Itoa(day1)
- }
- return Ymd
- }
- // 时间格式去掉时分秒
- func TimeRemoveHms2(strTime string) string {
- var Ymd string
- var resultTime = StrTimeToTime(strTime)
- year := resultTime.Year()
- month := resultTime.Format("01")
- day1 := resultTime.Day()
- if day1 < 10 {
- Ymd = strconv.Itoa(year) + "-" + month + "-0" + strconv.Itoa(day1)
- } else {
- Ymd = strconv.Itoa(year) + "-" + month + "-" + strconv.Itoa(day1)
- }
- return Ymd
- }
- // 判断时间是当年的第几周
- func WeekByDate(t time.Time) string {
- var resultSAtr string
- //t = t.AddDate(0, 0, -8) // 减少八天跟老数据标题统一
- //yearDay := t.YearDay()
- //yearFirstDay := t.AddDate(0, 0, -yearDay+1)
- //firstDayInWeek := int(yearFirstDay.Weekday())
- //今年第一周有几天
- //firstWeekDays := 1
- //if firstDayInWeek != 0 {
- // firstWeekDays = 7 - firstDayInWeek + 1
- //}
- //if yearDay <= firstWeekDays {
- // week = 1
- //} else {
- // week = (yearDay-firstWeekDays)/7 + 2
- //}
- var week int
- _, week = t.ISOWeek()
- resultSAtr = "(" + strconv.Itoa(t.Year()) + "年第" + strconv.Itoa(week) + "周" + ")"
- return resultSAtr
- }
- func Mp3Time(videoPlaySeconds string) string {
- var d int
- var timeStr string
- a, _ := strconv.ParseFloat(videoPlaySeconds, 32)
- b := int(a)
- if b <= 60 {
- timeStr = "00:" + strconv.Itoa(b)
- } else {
- c := b % 60
- d = b / 60
- if d < 10 {
- timeStr = "0" + strconv.Itoa(d) + ":" + strconv.Itoa(c)
- } else {
- timeStr = strconv.Itoa(d) + ":" + strconv.Itoa(c)
- }
- }
- return timeStr
- }
- // 用户参会时间转换
- func GetAttendanceDetailSeconds(secondNum int) string {
- var timeStr string
- if secondNum <= 60 {
- if secondNum < 10 {
- timeStr = "0" + strconv.Itoa(secondNum) + "''"
- } else {
- timeStr = strconv.Itoa(secondNum) + "''"
- }
- } else {
- var remainderStr string
- remainderNum := secondNum % 60
- minuteNum := secondNum / 60
- if remainderNum < 10 {
- remainderStr = "0" + strconv.Itoa(remainderNum) + "''"
- } else {
- remainderStr = strconv.Itoa(remainderNum) + "''"
- }
- if minuteNum < 10 {
- timeStr = "0" + strconv.Itoa(minuteNum) + "'" + remainderStr
- } else {
- timeStr = strconv.Itoa(minuteNum) + "'" + remainderStr
- }
- }
- return timeStr
- }
- // 用户参会时间转换
- func GetAttendanceDetailSecondsByYiDong(str string) string {
- var timeStr string
- timeStr = strings.Replace(str, ":", "'", -1)
- timeStr += "''"
- return timeStr
- }
- // GetOrmInReplace 获取orm的in查询替换?的方法
- func GetOrmInReplace(num int) string {
- template := make([]string, num)
- for i := 0; i < num; i++ {
- template[i] = "?"
- }
- return strings.Join(template, ",")
- }
- func GetLocalIP() (ip string, err error) {
- addrs, err := net.InterfaceAddrs()
- if err != nil {
- return
- }
- for _, addr := range addrs {
- ipAddr, ok := addr.(*net.IPNet)
- if !ok {
- continue
- }
- if ipAddr.IP.IsLoopback() {
- continue
- }
- if !ipAddr.IP.IsGlobalUnicast() {
- continue
- }
- return ipAddr.IP.String(), nil
- }
- return
- }
- // 字符串类型时间转周几
- func StrDateTimeToWeek(strTime string) string {
- var WeekDayMap = map[string]string{
- "Monday": "周一",
- "Tuesday": "周二",
- "Wednesday": "周三",
- "Thursday": "周四",
- "Friday": "周五",
- "Saturday": "周六",
- "Sunday": "周日",
- }
- var ctime = StrTimeToTime(strTime).Format("2006-01-02")
- startday, _ := time.Parse("2006-01-02", ctime)
- staweek_int := startday.Weekday().String()
- return WeekDayMap[staweek_int]
- }
- // ReplaceSpaceAndWrap 去除空格跟换行
- func ReplaceSpaceAndWrap(str string) string {
- // 去除空格
- str = strings.Replace(str, " ", "", -1)
- // 去除换行符
- str = strings.Replace(str, "\n", "", -1)
- return str
- }
- // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该int值)
- func InArrayByInt(idIntList []int, searchId int) (has bool) {
- for _, id := range idIntList {
- if id == searchId {
- has = true
- return
- }
- }
- return
- }
- // InArrayByStr php中的in_array(判断String类型的切片中是否存在该string值)
- func InArrayByStr(idStrList []string, searchId string) (has bool) {
- for _, id := range idStrList {
- if id == searchId {
- has = true
- return
- }
- }
- return
- }
- // GetNowWeekMonday 获取本周周一的时间
- func GetNowWeekMonday() time.Time {
- offset := int(time.Monday - time.Now().Weekday())
- if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
- offset = -6
- }
- mondayTime := time.Now().AddDate(0, 0, offset)
- mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
- return mondayTime
- }
- // GetLastWeekMonday 获取上周周一的时间
- func GetLastWeekMonday() time.Time {
- offset := int(time.Monday - time.Now().Weekday())
- if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
- offset = -6
- }
- mondayTime := time.Now().AddDate(0, 0, offset-7)
- mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
- return mondayTime
- }
- // GetNowWeekSunDay 获取本周周日的时间
- func GetNowWeekSunday() time.Time {
- return GetNowWeekMonday().AddDate(0, 0, 6)
- }
- // GetLastWeekSunday 获取上周周日的时间
- func GetLastWeekSunday() time.Time {
- return GetLastWeekMonday().AddDate(0, 0, 6)
- }
- // GetNowMonthFirstDay 获取本月第一天的时间
- func GetNowMonthFirstDay() time.Time {
- nowMonthFirstDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location())
- return nowMonthFirstDay
- }
- // GetNowMonthLastDay 获取本月最后一天的时间
- func GetNowMonthLastDay() time.Time {
- nowMonthLastDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
- nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
- return nowMonthLastDay
- }
- // GetNowMonthFirstDay 获取上月第一天的时间
- func GetLastMonthFirstDay() time.Time {
- nowMonthFirstDay := time.Date(time.Now().Year(), time.Now().AddDate(0, -1, 0).Month(), 1, 0, 0, 0, 0, time.Now().Location())
- return nowMonthFirstDay
- }
- // GetNowMonthLastDay 获取上月最后一天的时间
- func GetLastMonthLastDay() time.Time {
- nowMonthLastDay := time.Date(time.Now().Year(), time.Now().AddDate(0, -1, 0).Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
- nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
- return nowMonthLastDay
- }
- // 字符串转换为time
- func StrDateToTime(strTime string) time.Time {
- timeLayout := "2006-01-02" //转化所需模板
- loc, _ := time.LoadLocation("Local") //重要:获取时区
- resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
- return resultTime
- }
- // 获取时间的月跟日
- func GetTimeDateHourAndDay(DayTime time.Time) (dataStr string) {
- dataSlice := strings.Split(DayTime.Format(FormatDate), "-")
- for k, v := range dataSlice {
- if k == 0 {
- continue
- }
- dataStr += v + "."
- }
- dataStr = strings.TrimRight(dataStr, ".")
- return
- }
- // 时间格式去掉年
- func GetTimeDateRemoveYear(strTime string) (dataStr string) {
- slicePublishTime := strings.Split(strTime, "-")
- for k, v := range slicePublishTime {
- if k == 0 {
- continue
- }
- dataStr += v + "-"
- }
- dataStr = strings.TrimRight(dataStr, "-")
- return dataStr
- }
- // 时间格式去掉年和秒
- func GetTimeDateRemoveYearAndSecond(strTime string) (dataStr string) {
- slicePublishTime := strings.Split(strTime, "-")
- for k, v := range slicePublishTime {
- if k == 0 {
- continue
- }
- dataStr += v + "-"
- }
- dataStr = strings.TrimRight(dataStr, "-")
- dataStr = dataStr[:len(dataStr)-3]
- return
- }
- func ArticleHasImgUrl(body string) (hasImg bool, err error) {
- r := strings.NewReader(string(body))
- doc, err := goquery.NewDocumentFromReader(r)
- if err != nil {
- fmt.Println(err)
- }
- doc.Find("img").Each(func(i int, s *goquery.Selection) {
- hasImg = true
- })
- return
- }
- func ArticleHasStyle(body string) (hasStyle bool, err error) {
- r := strings.NewReader(string(body))
- doc, err := goquery.NewDocumentFromReader(r)
- if err != nil {
- fmt.Println(err)
- }
- doc.Find("p style").Each(func(i int, s *goquery.Selection) {
- hasStyle = true
- })
- doc.Find("class").Each(func(i int, s *goquery.Selection) {
- hasStyle = true
- })
- doc.Find("strong").Each(func(i int, s *goquery.Selection) {
- hasStyle = true // 加粗
- })
- doc.Find("u").Each(func(i int, s *goquery.Selection) {
- hasStyle = true // 下划线
- })
- return
- }
- func ArticleRemoveImgUrl(body string) (result string) {
- // 使用正则表达式去除img标签
- re := regexp.MustCompile(`<img[^>]*>`)
- result = re.ReplaceAllString(body, "")
- return
- }
- func FindArticleImgUrls(body string) (imgUrls []string, err error) {
- r := strings.NewReader(string(body))
- doc, err := goquery.NewDocumentFromReader(r)
- if err != nil {
- fmt.Println(err)
- }
- doc.Find("img").Each(func(i int, s *goquery.Selection) {
- src, _ := s.Attr("src")
- imgUrls = append(imgUrls, src)
- })
- return
- }
- // 去除部分style
- func ExtractText(body string) (result string, err error) {
- // 使用正则表达式去除img标签
- re := regexp.MustCompile(`<section style[\s\S]*?>`)
- result = re.ReplaceAllString(body, "")
- re = regexp.MustCompile(`<span style[\s\S]*?>`)
- result = re.ReplaceAllString(result, "")
- return
- }
- // 提取的纯文本内容
- func GetHtmlContentText(content string) (contentSub string, err error) {
- if content == "" {
- return
- }
- content = html.UnescapeString(content)
- doc, err := goquery.NewDocumentFromReader(strings.NewReader(content))
- if err != nil {
- return
- }
- docText := doc.Text()
- bodyRune := []rune(docText)
- bodyRuneLen := len(bodyRune)
- body := string(bodyRune[:bodyRuneLen])
- contentSub = body
- return
- }
- // 富文本字符串截取指定长度
- func InterceptHtmlLength(body string, length int) (newbody string) {
- content := html.UnescapeString(body)
- doc, err := goquery.NewDocumentFromReader(strings.NewReader(content))
- if err != nil {
- fmt.Println("create doc err:", err.Error())
- return
- }
- bodyText := doc.Text()
- //if len(bodyText) < length {
- // length = len(bodyText)
- //}
- //newbody = bodyText[0:length]
- totalCharCount := utf8.RuneCountInString(bodyText)
- if totalCharCount < length {
- length = len(bodyText)
- }
- // 计算前15个汉字所需的字节位置
- hanziCount := 0
- byteIndex := 0
- for byteIndex < len(bodyText) && hanziCount < length {
- r, size := utf8.DecodeRuneInString(bodyText[byteIndex:])
- if r != utf8.RuneError {
- hanziCount++
- }
- byteIndex += size
- }
- newbody = bodyText[:byteIndex] + "…"
- return
- }
- // 获取字符串中的阿拉伯数字,并返回字符串
- func GetArabicNumbers(str string) string {
- var numbers []rune
- for _, char := range str {
- if unicode.IsDigit(char) {
- numbers = append(numbers, char)
- }
- }
- return string(numbers)
- }
- // 处理活动名称
- func TruncateActivityNameString(s string) string {
- // 计算字符串总字数(按汉字、数字、字母和特殊符号计算)
- totalCharCount := utf8.RuneCountInString(s)
- // 如果总字数不超过18,则直接返回整个字符串
- if totalCharCount <= 18 {
- return s
- }
- // 计算前15个汉字所需的字节位置
- hanziCount := 0
- byteIndex := 0
- for byteIndex < len(s) && hanziCount < 15 {
- r, size := utf8.DecodeRuneInString(s[byteIndex:])
- if r != utf8.RuneError {
- hanziCount++
- }
- byteIndex += size
- }
- // 截取前15个汉字,并添加省略号
- return s[:byteIndex] + "…"
- }
- // 根据字符串时间格式获取所在时间段周一、周日
- func GetMondayAndSundayByTimeString(timeString string) (monday, sunday string) {
- now := StrTimeToTime(timeString)
- mondayDate := now.AddDate(0, 0, -int(now.Weekday()-time.Monday))
- // 计算当前周的周日
- sundayDate := mondayDate.AddDate(0, 0, 6)
- monday = mondayDate.Format(FormatDate)
- sunday = sundayDate.Format(FormatDate)
- return
- }
- // HmacSha256 计算HmacSha256
- // key 是加密所使用的key
- // data 是加密的内容
- func HmacSha256(key string, data string) []byte {
- mac := hmac.New(sha256.New, []byte(key))
- _, _ = mac.Write([]byte(data))
- return mac.Sum(nil)
- }
- // HmacSha256ToBase64 将加密后的二进制转Base64字符串
- func HmacSha256ToBase64(key string, data string) string {
- return base64.URLEncoding.EncodeToString(HmacSha256(key, data))
- }
- func GetSignFiccYbEtaHub(nonce, timestamp string) (sign string) {
- signStrMap := map[string]string{
- "nonce": nonce,
- "timestamp": timestamp,
- "appid": FiccYbEtaHubAppId,
- }
- keys := make([]string, 0, len(signStrMap))
- for k := range signStrMap {
- keys = append(keys, k)
- }
- sort.Strings(keys)
- var signStr string
- for _, k := range keys {
- signStr += k + "=" + signStrMap[k] + "&"
- }
- signStr = strings.Trim(signStr, "&")
- sign = HmacSha256ToBase64(FiccYbEtaHubSecret, signStr)
- return
- }
|