123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715 |
- package lib
- import (
- "AIOTCOER/logs"
- "bytes"
- "crypto/sha256"
- "encoding/hex"
- "encoding/json"
- "fmt"
- "github.com/nats-io/nats.go"
- "github.com/thinkeridea/go-extend/exunicode/exutf8"
- "go.mongodb.org/mongo-driver/bson"
- "golang.org/x/text/encoding/simplifiedchinese"
- "golang.org/x/text/transform"
- "io/ioutil"
- "math/rand"
- "reflect"
- "runtime"
- "strconv"
- "strings"
- "sync"
- "time"
- "unicode/utf8"
- )
- var Nats *nats.Conn
- type SingleMutex struct {
- Mu sync.RWMutex
- Num int64
- }
- var PullHandleTime SingleMutex
- //耗时统计函数
- func (c *SingleMutex) TimeCost(start time.Time){
- c.Mu.Lock()
- c.Num = time.Since(start).Milliseconds()
- c.Mu.Unlock()
- }
- func init() {
- }
- const Success = 200
- const Error = 201
- type JSONR struct {
- //必须的大写开头
- Code int16
- Msg string
- Data interface{} // 泛型
- }
- type JSONS struct {
- //必须的大写开头
- Code int16
- Msg string
- List interface{}
- Total int16
- PageIndex int
- PageSize int
- }
- func C_Page(list interface{}, PageIndex, PageSize int, Total int64) (Jsons JSONS) {
- Jsons.List = list
- Jsons.Total = int16(Total)
- Jsons.PageIndex = PageIndex
- Jsons.PageSize = PageSize
- //Jsons.PageSize = int16(math.Ceil(float64(Total) / float64(PageSize)))
- return Jsons
- }
- func Strval(value interface{}) string {
- var key string
- if value == nil {
- return key
- }
- switch value.(type) {
- case float64:
- ft := value.(float64)
- key = strconv.FormatFloat(ft, 'f', -1, 64)
- case float32:
- ft := value.(float32)
- key = strconv.FormatFloat(float64(ft), 'f', -1, 64)
- case int:
- it := value.(int)
- key = strconv.Itoa(it)
- case uint:
- it := value.(uint)
- key = strconv.Itoa(int(it))
- case int8:
- it := value.(int8)
- key = strconv.Itoa(int(it))
- case uint8:
- it := value.(uint8)
- key = strconv.Itoa(int(it))
- case int16:
- it := value.(int16)
- key = strconv.Itoa(int(it))
- case uint16:
- it := value.(uint16)
- key = strconv.Itoa(int(it))
- case int32:
- it := value.(int32)
- key = strconv.Itoa(int(it))
- case uint32:
- it := value.(uint32)
- key = strconv.Itoa(int(it))
- case int64:
- it := value.(int64)
- key = strconv.FormatInt(it, 10)
- case uint64:
- it := value.(uint64)
- key = strconv.FormatUint(it, 10)
- case string:
- key = value.(string)
- case []byte:
- key = string(value.([]byte))
- default:
- newValue, _ := json.Marshal(value)
- key = string(newValue)
- }
- return key
- }
- // 取一个
- func Take_one(a, b string) string {
- if len(a) == 0 {
- return b
- }
- return a
- }
- func To_int(value interface{}) int {
- var key int
- if value == nil {
- return key
- }
- switch value.(type) {
- case float64:
- key = int(value.(float64))
- case float32:
- key = int(value.(float32))
- case int:
- key = int(value.(int))
- case uint:
- key = int(value.(uint))
- case int8:
- key = int(value.(int8))
- case uint8:
- key = int(value.(uint8))
- case int16:
- key = int(value.(int16))
- case uint16:
- key = int(value.(uint16))
- case int32:
- key = int(value.(int32))
- case uint32:
- key = int(value.(uint32))
- case int64:
- key = int(value.(int64))
- case uint64:
- key = int(value.(uint64))
- case string:
- key, _ = strconv.Atoi(value.(string))
- case []byte:
- key, _ = strconv.Atoi(string(value.([]byte)))
- default:
- newValue, _ := json.Marshal(value)
- key, _ = strconv.Atoi(string(newValue))
- }
- return key
- }
- func To_int64(value interface{}) int64 {
- var key int64
- if value == nil {
- return key
- }
- switch value.(type) {
- case float64:
- key = int64(value.(float64))
- case float32:
- key = int64(value.(float32))
- case int:
- key = int64(value.(int))
- case uint:
- key = int64(value.(uint))
- case int8:
- key = int64(value.(int8))
- case uint8:
- key = int64(value.(uint8))
- case int16:
- key = int64(value.(int16))
- case uint16:
- key = int64(value.(uint16))
- case int32:
- key = int64(value.(int32))
- case uint32:
- key = int64(value.(uint32))
- case int64:
- key = int64(value.(int64))
- case uint64:
- key = int64(value.(uint64))
- case string:
- key, _ = strconv.ParseInt(value.(string), 10, 64)
- case []byte:
- key, _ = strconv.ParseInt(string(value.([]byte)), 10, 64)
- default:
- newValue, _ := json.Marshal(value)
- key, _ = strconv.ParseInt(string(newValue), 10, 64)
- }
- return key
- }
- func To_float32(value interface{}) float32 {
- var key float32
- if value == nil {
- return key
- }
- switch value.(type) {
- case float64:
- key = float32(value.(float64))
- case float32:
- key = float32(value.(float32))
- case int:
- key = float32(value.(int))
- case uint:
- key = float32(value.(uint))
- case int8:
- key = float32(value.(int8))
- case uint8:
- key = float32(value.(uint8))
- case int16:
- key = float32(value.(int16))
- case uint16:
- key = float32(value.(uint16))
- case int32:
- key = float32(value.(int32))
- case uint32:
- key = float32(value.(uint32))
- case int64:
- key = float32(value.(int64))
- case uint64:
- key = float32(value.(uint64))
- case string:
- key_float64, _ := strconv.ParseFloat(value.(string), 32/64)
- key = float32(key_float64)
- case []byte:
- key_float64, _ := strconv.ParseFloat(string(value.([]byte)), 32/64)
- key = float32(key_float64)
- default:
- newValue, _ := json.Marshal(value)
- key_float64, _ := strconv.ParseFloat(string(newValue), 32/64)
- key = float32(key_float64)
- }
- key_float64, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", key), 32/64)
- key = float32(key_float64)
- return key
- }
- func To_string(value interface{}) string {
- var key string
- if value == nil {
- return key
- }
- switch value.(type) {
- case float64:
- ft := value.(float64)
- key = strconv.FormatFloat(ft, 'f', -1, 64)
- case float32:
- ft := value.(float32)
- key = strconv.FormatFloat(float64(ft), 'f', -1, 64)
- case int:
- it := value.(int)
- key = strconv.Itoa(it)
- case uint:
- it := value.(uint)
- key = strconv.Itoa(int(it))
- case int8:
- it := value.(int8)
- key = strconv.Itoa(int(it))
- case uint8:
- it := value.(uint8)
- key = strconv.Itoa(int(it))
- case int16:
- it := value.(int16)
- key = strconv.Itoa(int(it))
- case uint16:
- it := value.(uint16)
- key = strconv.Itoa(int(it))
- case int32:
- it := value.(int32)
- key = strconv.Itoa(int(it))
- case uint32:
- it := value.(uint32)
- key = strconv.Itoa(int(it))
- case int64:
- it := value.(int64)
- key = strconv.FormatInt(it, 10)
- case uint64:
- it := value.(uint64)
- key = strconv.FormatUint(it, 10)
- case string:
- key = value.(string)
- case []byte:
- key = string(value.([]byte))
- default:
- newValue, _ := json.Marshal(value)
- key = string(newValue)
- }
- return key
- }
- func Random(min, max int) int {
- rand.Seed(time.Now().Unix()) //Seed生成的随机数
- return rand.Intn(max-min) + min
- }
- // 取文本(字符串)中间
- func GetBetweenStr(str, start, end string) string {
- n := strings.Index(str, start)
- if n == -1 {
- n = 0
- } else {
- n = n + len(start) // 增加了else,不加的会把start带上
- }
- str = string([]byte(str)[n:])
- m := strings.Index(str, end)
- if m == -1 {
- m = len(str)
- }
- str = string([]byte(str)[:m])
- return str
- }
- // getYearMonthToDay 查询指定年份指定月份有多少天
- // @params year int 指定年份
- // @params month int 指定月份
- func GetYearMonthToDay(year int, month int) int {
- // 有31天的月份
- day31 := map[int]bool{
- 1: true,
- 3: true,
- 5: true,
- 7: true,
- 8: true,
- 10: true,
- 12: true,
- }
- if day31[month] == true {
- return 31
- }
- // 有30天的月份
- day30 := map[int]bool{
- 4: true,
- 6: true,
- 9: true,
- 11: true,
- }
- if day30[month] == true {
- return 30
- }
- // 计算是平年还是闰年
- if (year%4 == 0 && year%100 != 0) || year%400 == 0 {
- // 得出2月的天数
- return 29
- }
- // 得出2月的天数
- return 28
- }
- func Decimal(value float64) float64 {
- value, _ = strconv.ParseFloat(fmt.Sprintf("%.1f", value), 64)
- return value
- }
- func Strconv_Atoi(string string) int {
- int, _ := strconv.Atoi(string)
- return int
- }
- // 获取正在运行的函数名
- func FuncName() string {
- pc := make([]uintptr, 1)
- runtime.Callers(2, pc)
- f := runtime.FuncForPC(pc[0])
- return f.Name()
- }
- func Limit_len(str string, lenx int) string {
- if utf8.RuneCountInString(str) > lenx {
- return exutf8.RuneSubString(str, 0, lenx-3) + "..."
- }
- return exutf8.RuneSubString(str, 0, lenx)
- }
- func Utf8ToGbk(s []byte) ([]byte, error) {
- reader := transform.NewReader(bytes.NewReader(s), simplifiedchinese.GBK.NewEncoder())
- d, e := ioutil.ReadAll(reader)
- if e != nil {
- return nil, e
- }
- return d, nil
- }
- // #取得随机字符串:通过打乱slice来操作
- func GetRandstring(length int, char string, rand_x int64) string {
- if length < 1 {
- return ""
- }
- if len(char) <= 6 || len(char) <= length {
- char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
- }
- charArr := strings.Split(char, "")
- ran := rand.New(rand.NewSource(time.Now().Unix() + rand_x))
- l := len(charArr)
- for i := l - 1; i > 0; i-- {
- r := ran.Intn(i)
- charArr[r], charArr[i] = charArr[i], charArr[r]
- }
- rchar := charArr[:length]
- return strings.Join(rchar, "")
- }
- // Sha256加密
- func Sha256(src string) string {
- m := sha256.New()
- m.Write([]byte(src))
- res := hex.EncodeToString(m.Sum(nil))
- return res
- }
- // 判断时间是当年的第几周
- func WeekByDate() string {
- t := time.Now()
- yearDay := t.YearDay()
- yearFirstDay := t.AddDate(0, 0, -yearDay+1)
- firstDayInWeek := int(yearFirstDay.Weekday())
- //今年第一周有几天
- firstWeekDays := 1
- if firstDayInWeek != 0 {
- firstWeekDays = 7 - firstDayInWeek + 1
- }
- var week int
- if yearDay <= firstWeekDays {
- week = 1
- } else {
- week = (yearDay-firstWeekDays)/7 + 2
- }
- return fmt.Sprintf("%d%02d", t.Year(), week) // 202253
- }
- // 获取json指定参数 [AAAA BBBB],0,JSON !!!如果失败,返回已找到的全部json
- func Json_key(topicNameList []string, topicNameI int, articleSlide map[string]interface{}) interface{} {
- if len(topicNameList) > topicNameI {
- a, is := articleSlide[topicNameList[topicNameI]]
- if !is {
- return articleSlide
- }
- if reflect.TypeOf(a).String() == "map[string]interface {}" {
- return Json_key(topicNameList, topicNameI+1, a.(map[string]interface{}))
- }
- }
- if len(topicNameList) == topicNameI {
- return articleSlide
- }
- return articleSlide[topicNameList[topicNameI]]
- }
- // 导出map到文件
- func MapToFile(data map[string]map[string]string, filePath string) error {
- jsonData, err := json.Marshal(data)
- if err != nil {
- return err
- }
- err = ioutil.WriteFile(filePath, jsonData, 0644)
- if err != nil {
- return err
- }
- return nil
- }
- // 从文件中导入map数据
- func MapFromFile(filePath string) map[string]map[string]string {
- jsonData, err := ioutil.ReadFile(filePath)
- if err != nil {
- return nil
- }
- var importedMap map[string]map[string]string
- err = json.Unmarshal(jsonData, &importedMap)
- if err != nil {
- logs.PrintlnError("Error unmarshalling JSON:", err)
- return nil
- }
- return importedMap
- }
- func Hande_Tab_Tfilter(ArticleSlide []map[string]interface{}, JointTab string, t_map *[]string) {
- for _, value := range ArticleSlide {
- // 存在下一级
- if len(JointTab) == 0 || len(value["children"].([]interface{})) != 0 {
- key := JointTab + value["T_tab"].(string)
- if value["T_filter"] == nil {
- continue
- }
- if reflect.TypeOf(value["T_filter"]).String() != "bool" {
- continue
- }
- key_v := value["T_filter"].(bool)
- if key_v {
- //(*t_map)[key] = key_v
- (*t_map) = append((*t_map), key)
- }
- if len(value["children"].([]interface{})) != 0 {
- var valuex_map []map[string]interface{}
- for _, valuex := range value["children"].([]interface{}) {
- if reflect.TypeOf(valuex).String() == "map[string]interface {}" {
- valuex_map = append(valuex_map, valuex.(map[string]interface{}))
- }
- }
- Hande_Tab_Tfilter(valuex_map, key+".", t_map)
- }
- }
- }
- }
- func Hande_Tab_Trenew(ArticleSlide []map[string]interface{}, JointTab string, t_map *[]string) {
- for _, value := range ArticleSlide {
- // 存在下一级
- key := JointTab + value["T_tab"].(string)
- if len(value["children"].([]interface{})) != 0 {
- var valuex_map []map[string]interface{}
- for _, valuex := range value["children"].([]interface{}) {
- if reflect.TypeOf(valuex).String() == "map[string]interface {}" {
- valuex_map = append(valuex_map, valuex.(map[string]interface{}))
- }
- }
- Hande_Tab_Trenew(valuex_map, key+".", t_map)
- }
- if value["T_renew"] == nil {
- continue
- }
- if reflect.TypeOf(value["T_renew"]).String() != "bool" {
- continue
- }
- key_v := value["T_renew"].(bool)
- if key_v {
- //(*t_map)[key] = key_v
- (*t_map) = append((*t_map), key)
- }
- }
- }
- func Hande_Tab_Tsave(ArticleSlide []map[string]interface{}, JointTab string, t_map *map[string]int) {
- for _, value := range ArticleSlide {
- // 存在下一级
- if len(JointTab) == 0 || len(value["children"].([]interface{})) != 0 {
- key := JointTab + value["T_tab"].(string)
- if value["T_save"] == nil {
- continue
- }
- key_v := To_int(value["T_save"])
- if key_v > 0 {
- (*t_map)[key] = key_v
- }
- if len(value["children"].([]interface{})) != 0 {
- var valuex_map []map[string]interface{}
- for _, valuex := range value["children"].([]interface{}) {
- if reflect.TypeOf(valuex).String() == "map[string]interface {}" {
- valuex_map = append(valuex_map, valuex.(map[string]interface{}))
- }
- }
- Hande_Tab_Tsave(valuex_map, key+".", t_map)
- }
- }
- }
- }
- // 通过 "aa.bb.cc" 获取map指定参数
- func GetMapRecursion(str string, nestedMap map[string]interface{}) interface{} {
- keys := strings.Split(str, ".")
- result := nestedMap
- for _, key := range keys {
- if value, ok := result[key]; ok {
- switch reflect.TypeOf(value).String() {
- case "map[string]interface {}":
- result = value.(map[string]interface{})
- break
- default:
- return value
- }
- } else {
- logs.Println("Key not found")
- return nil
- }
- }
- return result
- }
- // 将 时间格式为 bson.M 时间格式
- func MongdbJsonHtime(ArticleSlide bson.M) bson.M {
- bson_M := bson.M{}
- for key, value := range ArticleSlide {
- //logs.Println(reflect.TypeOf(value).String())
- switch reflect.TypeOf(value).String() {
- case "map[string]interface {}":
- jsonFind_M := bson.M{}
- data, _ := json.Marshal(value.(map[string]interface{}))
- err := json.Unmarshal(data, &jsonFind_M)
- if err == nil {
- bson_M[key] = MongdbJsonHtime(jsonFind_M)
- }
- break
- case "[]interface {}":
- bson_M_list := []bson.M{}
- for _, valuex := range value.([]interface{}) {
- if reflect.TypeOf(valuex).String() == "map[string]interface {}" {
- jsonFind_M := bson.M{}
- data, _ := json.Marshal(valuex.(map[string]interface{}))
- err := json.Unmarshal(data, &jsonFind_M)
- if err == nil {
- bson_M_list = append(bson_M_list, MongdbJsonHtime(jsonFind_M))
- }
- }
- }
- bson_M[key] = bson_M_list
- //return json_r
- break
- default:
- t1, err := time.ParseInLocation("2006-01-02 15:04:05", value.(string), time.Local) // +8 时差
- if err == nil {
- bson_M[key] = t1
- } else {
- bson_M[key] = value
- }
- break
- }
- }
- return bson_M
- }
- // 判断字符串是否在数组中
- func StringExistsInSlice(str string, slice []string) bool {
- for _, s := range slice {
- if s == str {
- return true
- }
- }
- return false
- }
- // 获取 JSON 指定位置 field : "AAA.BBB.d_name"
- func JsonGetField(data map[string]interface{}, field string) interface{} {
- fields := strings.Split(field, ".")
- result := data
- for _, f := range fields {
- if val, ok := result[f]; ok {
- switch val.(type) {
- case map[string]interface{}:
- result = val.(map[string]interface{})
- default:
- return val
- }
- } else {
- return nil
- }
- }
- return result
- }
- // 获取 JSON 指定位置 data:修改的field必须存在 field : "AAA.BBB.d_name" value: 123
- func JsonSetField(data map[string]interface{}, field string, value interface{}) {
- fields := strings.Split(field, ".")
- current := data
- for i, fieldv := range fields {
- if i == len(fields)-1 {
- current[fieldv] = value
- } else {
- next, ok := current[fieldv].(map[string]interface{})
- if !ok {
- return
- }
- current = next
- }
- }
- }
- // 复制一份 Map
- func CopyMap(inputMap map[string]interface{}) map[string]interface{} {
- copiedMap := make(map[string]interface{})
- for key, value := range inputMap {
- copiedMap[key] = value
- }
- return copiedMap
- }
|