zhangzengfei
2024-09-29 3737ab3dd0cc753be986638316c96cb3114601e4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package util
 
import (
    "basic.com/valib/logger.git"
    "bytes"
    "encoding/json"
    "errors"
    "fmt"
    "math"
    "os/exec"
    "strconv"
    "time"
)
 
// 脚本封装
func RunScript(str string) string {
    cmd := exec.Command("sh", "-c", str)
    var out bytes.Buffer
    cmd.Stdout = &out
    err := cmd.Run()
    if err != nil {
        return "运行失败"
    }
    return out.String()
}
 
func Sourcelist(buf []byte) (sources []map[string]interface{}, err error) {
    var info interface{}
    json.Unmarshal(buf, &info)
    out, ok := info.(map[string]interface{})
    if !ok {
        return nil, errors.New("http response interface can not change map[string]interface{}")
    }
 
    middle, ok := out["hits"].(map[string]interface{})
    if !ok {
        return nil, errors.New("first hits change error!")
    }
    for _, in := range middle["hits"].([]interface{}) {
        tmpbuf, ok := in.(map[string]interface{})
        if !ok {
            fmt.Println("change to source error!")
            continue
        }
        source, ok := tmpbuf["_source"].(map[string]interface{})
        if !ok {
            fmt.Println("change _source error!")
            continue
        }
        sources = append(sources, source)
    }
    return sources, nil
}
 
func SourceTotal(buf []byte) (total int, err error) {
    var info interface{}
    json.Unmarshal(buf, &info)
    out, ok := info.(map[string]interface{})
    if !ok {
        return -1, errors.New("http response interface can not change map[string]interface{}")
    }
 
    middle, ok := out["hits"].(map[string]interface{})
    if !ok {
        return -1, errors.New("first total change error!")
    }
 
    tmp, b := middle["total"].(map[string]interface{})
    if b != true {
        v := middle["total"].(float64)
        t := int(v)
        return t, nil
    }
    value := tmp["value"].(float64)
    total = int(value)
    return total, nil
}
 
func SourceCreated(buf []byte) (result bool, err error) {
    var info interface{}
    json.Unmarshal(buf, &info)
    out, ok := info.(map[string]interface{})
    if !ok {
        return false, errors.New("http response interface can not change map[string]interface{}")
    }
 
    middle, ok := out["result"].(string)
    if !ok {
        return false, errors.New("first total change error!")
    }
    if middle == "created" || middle == "updated" {
        result = true
    }
    return result, nil
}
 
func SourceDeleted(buf []byte) (total int, err error) {
    var info interface{}
    json.Unmarshal(buf, &info)
    out, ok := info.(map[string]interface{})
    if !ok {
        return -1, errors.New("http response interface can not change map[string]interface{}")
    }
 
    middle, ok := out["deleted"].(float64)
    if !ok {
        return -1, errors.New("first total change error!")
    }
    total = int(middle)
    return total, nil
}
 
func SourceUpdated(buf []byte) (total int, err error) {
    var info interface{}
    json.Unmarshal(buf, &info)
    out, ok := info.(map[string]interface{})
    if !ok {
        return -1, errors.New("http response interface can not change map[string]interface{}")
    }
    //fmt.Println(out)
    middle, ok := out["updated"].(float64)
    if !ok {
        return -1, errors.New("first total change error!")
    }
    total = int(middle)
    return total, nil
}
 
func SourceAggregationList(buf []byte) (sources []map[string]interface{}, err error) {
    var info interface{}
    json.Unmarshal(buf, &info)
    out, ok := info.(map[string]interface{})
    if !ok {
        return nil, errors.New("http response interface can not change map[string]interface{}")
    }
 
    middle, ok := out["aggregations"].(map[string]interface{})
    if !ok {
        return nil, errors.New("first hits change error!")
    }
 
    documentAggregations := middle["group_by_documentnumber"].(map[string]interface{})
    buckets := documentAggregations["buckets"].([]interface{})
    if len(buckets) == 0 {
        return nil, nil
    }
    for _, in := range buckets {
        tmpbuf, ok := in.(map[string]interface{})
        if !ok {
            return nil, errors.New("")
        }
        sources = append(sources, tmpbuf)
    }
    return sources, nil
}
 
func StartTimer(f func()) {
    for {
        f()
        now := time.Now()
        // 计算下一个零点
        next := now.Add(time.Hour * 24)
        next = time.Date(next.Year(), next.Month(), next.Day(), 0, 0, 0, 0, next.Location())
        t := time.NewTimer(next.Sub(now))
        <-t.C
        t.Stop()
    }
}
 
// 日期换算工具
func GetTimeArr(earliestDate string) int {
    now := time.Now().Format("2006-01-02")
    fmt.Println(earliestDate, now)
    a, _ := time.Parse("2006-01-02", earliestDate)
    b, _ := time.Parse("2006-01-02", now)
    d := a.Sub(b)
    date := d.Hours() / 24
    return int(math.Abs(date))
}
 
// 日期遍历工具
// GetBetweenDates 根据开始日期和结束日期计算出时间段内所有日期
// 参数为日期格式,如:2020-01-01
func GetBetweenDates(sdate, edate string) []string {
    d := []string{}
    timeFormatTpl := "2006-01-02"
    if len(timeFormatTpl) != len(sdate) {
        timeFormatTpl = timeFormatTpl[0:len(sdate)]
    }
    date, err := time.Parse(timeFormatTpl, sdate)
    if err != nil {
        // 时间解析,异常
        return d
    }
    date2, err := time.Parse(timeFormatTpl, edate)
    if err != nil {
        // 时间解析,异常
        return d
    }
    if date2.Before(date) {
        // 如果结束时间小于开始时间,异常
        return d
    }
    // 输出日期格式固定
    timeFormatTpl = "2006-01-02"
    date2Str := date2.Format(timeFormatTpl)
    d = append(d, date.Format(timeFormatTpl))
    for {
        date = date.AddDate(0, 0, 1)
        dateStr := date.Format(timeFormatTpl)
        d = append(d, dateStr)
        if dateStr == date2Str {
            break
        }
    }
    return d
}
 
func IpIntToString(ipInt int) string {
    ipSegs := make([]string, 4)
    var len int = len(ipSegs)
    buffer := bytes.NewBufferString("")
    for i := 0; i < len; i++ {
        tempInt := ipInt & 0xFF
        ipSegs[len-i-1] = strconv.Itoa(tempInt)
 
        ipInt = ipInt >> 8
    }
    for i := 0; i < len; i++ {
        buffer.WriteString(ipSegs[i])
        if i < len-1 {
            buffer.WriteString(".")
        }
    }
    return buffer.String()
}
 
// 计算时间阈值
func CheckTimeDifference(timestampStr1 string, timestampStr2 string, intervalInMinutes int) bool {
    layout := "2006-01-02 15:04:05"
    timestampStr1 = timestampStr1[:19]
    timestampStr2 = timestampStr2[:19]
    // 将字符串解析为时间
    time1, err := time.Parse(layout, timestampStr1)
    if err != nil {
        fmt.Println("时间解析失败:", err)
        return false
    }
    time2, err := time.Parse(layout, timestampStr2)
    if err != nil {
        fmt.Println("时间解析失败:", err)
        return false
    }
 
    // 计算时间差
    diff := time2.Sub(time1)
 
    // 检查时间差是否小于等于指定的间隔
    if diff.Minutes() <= float64(intervalInMinutes) {
        return true
    } else {
        return false
    }
}
 
func CalculateDays(startDate string, endDate string) int {
    layout := "2006-01-02" // 日期格式
    startTime, err := time.Parse(layout, startDate)
    if err != nil {
        // 错误处理
        logger.Error("Error parsing start date:", err)
        return 0
    }
 
    endTime, err := time.Parse(layout, endDate)
    if err != nil {
        // 错误处理
        logger.Error("Error parsing end date:", err)
        return 0
    }
 
    duration := endTime.Sub(startTime)
    days := int(duration.Hours() / 24) // 将时间差转换为天数
    return days
}