554325746@qq.com
2019-12-23 0222e79afe45d9fc55aed9a7e62ca239c228ab73
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package esutil
 
import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "io/ioutil"
    "log"
    "mime/multipart"
    "net/http"
    "strings"
    "time"
 
    "github.com/pkg/errors"
)
 
func GetEsDataReq(url string, parama string, isSource bool) map[string]interface{} {
    //fmt.Println("es 查询请求路径" + url) //  配置信息 获取
    var dat map[string]interface{}
    req, err := http.NewRequest("POST", url, strings.NewReader(parama))
    req.Header.Add("Content-Type", "application/json")
    timeout := time.Duration(10 * time.Second) //超时时间50ms
    client := &http.Client{Timeout: timeout}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println(err)
        return dat
    }
    defer resp.Body.Close()
    dec := json.NewDecoder(resp.Body)
    if err := dec.Decode(&dat); err == io.EOF {
        fmt.Println(err.Error())
        return dat
    } else if err != nil {
        fmt.Println(err.Error())
        return dat
    }
    // 是否需要 解析 es 返回的 source
    if isSource {
        dat = dat["hits"].(map[string]interface{})
        var data = make(map[string]interface{}, 2)
        data["total"] = dat["total"]
        sources := []interface{}{}
        for _, value := range dat["hits"].([]interface{}) {
            source := value.(map[string]interface{})["_source"].(map[string]interface{})
            //source["id"] = source["id"]
            /*sdkType := source["sdkType"]
            if sdkType != nil {
                sdk, _ := strconv.Atoi(sdkType.(string))
                source["sdkType"] = sdkTypeToValue(sdk)
            }*/
            sources = append(sources, source)
        }
        data["datalist"] = sources
        return data
    } else {
        return dat
    }
 
}
 
//sdk类型
/*func sdkTypeToValue(i int) string {
    value := []string{"人脸", "车辆", "人体", "入侵", "拥挤", "靠右行", "人员异常", "个体静止"}
    return value[i-1]
}*/
 
func PutEsDataReq(url string, parama string) (map[string]interface{}, error) {
    //fmt.Println("es 查询请求路径" + url) //  配置信息 获取
    req, err := http.NewRequest("PUT", url, strings.NewReader(parama))
    if err != nil {
        fmt.Println(err)
        return nil, err
    }
    req.Header.Add("Content-Type", "application/json")
    timeout := time.Duration(5 * time.Second) //超时时间50ms
    client := &http.Client{Timeout: timeout}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println(err)
        return nil, err
    }
    defer resp.Body.Close()
    if err != nil {
        fmt.Println(err)
        return nil, err
    }
    var dat map[string]interface{}
    dec := json.NewDecoder(resp.Body)
    if err := dec.Decode(&dat); err == io.EOF {
        fmt.Println(err.Error())
        return nil, err
    } else if err != nil {
        fmt.Println(err.Error())
        return nil, err
    }
    return dat, nil
}
 
func PostFormData(uri string, filename, paramName string, fileBytes []byte) (maps map[string]interface{}, err0 error) {
    body := &bytes.Buffer{}
    writer := multipart.NewWriter(body)
    _, err := writer.CreateFormFile(paramName, filename)
    if err != nil {
        return nil, err
    }
    boundary := writer.Boundary()
    close_buf := bytes.NewBufferString(fmt.Sprintf("\r\n--%s--\r\n", boundary))
    fmt.Println("PostFormData.fileLen:", len(fileBytes))
    file := bytes.NewBuffer(fileBytes)
    request_reader := io.MultiReader(body, file, close_buf)
 
    request, err := http.NewRequest("POST", uri, request_reader)
    request.Header.Add("Content-Type", writer.FormDataContentType())
    timeout := time.Duration(5 * time.Second) //超时时间50ms
    client := &http.Client{Timeout: timeout}
    resp, err := client.Do(request)
    if err != nil {
        log.Fatal(err)
        return nil, err
    }
    defer func() {
        if r := recover(); r != nil {
            fmt.Printf("panic的内容%v\n", r)
            msg := "上传图片服务器异常"
            if _, ok := r.(error); ok {
                msg = r.(error).Error()
                fmt.Println("panic--recover()得到的是error类型")
            }
            if _, ok := r.(string); ok {
                msg = r.(string)
                fmt.Println("panic--recover()得到的是string类型")
            }
            err0 = errors.New(msg)
        }
    }()
    defer resp.Body.Close()
    body = &bytes.Buffer{}
    _, err = body.ReadFrom(resp.Body)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(resp.StatusCode)
    //fmt.Println(body)
    //decoder := json.NewDecoder(strings.NewReader(body.String()))
    decoder := make(map[string]interface{})
    if err := json.Unmarshal([]byte(body.String()), &decoder); err != nil {
        return nil, err
    }
    return decoder, nil
}
 
func PostFormBufferData(uri string, filename, paramName string, fileData []byte) (maps map[string]interface{}, err0 error) {
    body := &bytes.Buffer{}
    writer := multipart.NewWriter(body)
    _, err := writer.CreateFormFile(paramName, filename)
    if err != nil {
        return nil, err
    }
    boundary := writer.Boundary()
    //close_string := fmt.Sprintf("\r\n--%s--\r\n", boundary)
    close_buf := bytes.NewBufferString(fmt.Sprintf("\r\n--%s--\r\n", boundary))
    file := bytes.NewBuffer(fileData)
    request_reader := io.MultiReader(body, file, close_buf)
    //_, err = io.Copy(part, file)
    //writer.WriteField(key, val)
    request, err := http.NewRequest("POST", uri, request_reader)
    request.Header.Add("Content-Type", writer.FormDataContentType())
    timeout := time.Duration(5 * time.Second) //超时时间50ms
    client := &http.Client{Timeout: timeout}
    resp, err := client.Do(request)
    if err != nil {
        log.Fatal(err)
        return nil, err
    }
    defer func() {
        if r := recover(); r != nil {
            fmt.Printf("panic的内容%v\n", r)
            msg := "上传图片服务器异常"
            if _, ok := r.(error); ok {
                msg = r.(error).Error()
                fmt.Println("panic--recover()得到的是error类型")
            }
            if _, ok := r.(string); ok {
                msg = r.(string)
                fmt.Println("panic--recover()得到的是string类型")
            }
            err0 = errors.New(msg)
        }
    }()
    defer resp.Body.Close()
    {
        body := &bytes.Buffer{}
        _, err := body.ReadFrom(resp.Body)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(resp.StatusCode)
        //fmt.Println(resp.Header)
        fmt.Println(body)
        //decoder := json.NewDecoder(strings.NewReader(body.String()))
        decoder := make(map[string]interface{})
        if err := json.Unmarshal([]byte(body.String()), &decoder); err != nil {
            return nil, err
        }
        return decoder, nil
    }
}
 
func GetEsDataInfo(url string, isSource bool) map[string]interface{} {
 
    fmt.Println("es GET 查询请求路径" + url) //  配置信息 获取
    req, err := http.NewRequest("GET", url, strings.NewReader(""))
    req.Header.Add("Content-Type", "application/json")
    timeout := time.Duration(5 * time.Second) //超时时间50ms
    client := &http.Client{Timeout: timeout}
    resp, err := client.Do(req)
    defer resp.Body.Close()
    if err != nil {
        fmt.Println(err)
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println(err)
    }
    //jsonStr := string(body)
    //fmt.Println("jsonStr", jsonStr)
    var dat map[string]interface{}
    if err := json.Unmarshal(body, &dat); err == nil {
        fmt.Println("token", dat["token"])
    } else {
        fmt.Println("json str to struct error")
    }
    // 是否需要 解析 es 返回的 source
    if isSource {
        source := make(map[string]interface{})
        if dat["_source"] != nil {
            source = dat["_source"].(map[string]interface{})
        }
        source["id"] = dat["_id"]
        return source
    } else {
        return dat
    }
}
 
//解析http
func EsReq(method string, url string, parama []byte) (buf []byte, err error) {
    timeout := time.Duration(10 * time.Second)
    client := http.Client{
        Timeout: timeout,
    }
    request, err := http.NewRequest(method, url, bytes.NewBuffer(parama))
    request.Header.Set("Content-type", "application/json")
 
    if err != nil {
        fmt.Println("build request fail !")
        return nil, err
    }
 
    resp, err := client.Do(request)
    if err != nil {
        fmt.Println("request error: ", err)
        return nil, err
    }
 
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println(err)
        return nil, err
    }
    return body, nil
}
 
//解析json
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 HttpGet(str string) ([]byte){
    resp, err :=   http.Get(str)
    if err != nil {
        // handle error
    }
 
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // handle error
    }
    return body
}