package esutil
|
|
import (
|
"encoding/json"
|
"errors"
|
"fmt"
|
"io/ioutil"
|
"net/http"
|
"time"
|
"bytes"
|
|
"basic.com/pubsub/protomsg.git"
|
)
|
|
|
func GetDbinfo(dbinforequest string)([]byte, error) {
|
buf , err := EsReq("POST", "http://192.168.1.182:9200/dbtablepersons/dbpersons/_search", []byte(dbinforequest))
|
return buf, err
|
}
|
|
|
func Parsesources(sources []map[string]interface{}) []protomsg.Baseinfo {
|
var tmpinfo protomsg.Baseinfo
|
var baseinfos []protomsg.Baseinfo
|
var ok bool
|
for _, source := range sources {
|
|
tmpinfo.FaceFeature, ok = source["faceFeature"].(string)
|
Isnil("faceFeature", ok)
|
tmpinfo.PersonId, ok = source["id"].(string)
|
Isnil("id", ok)
|
tmpinfo.TableId, ok = source["tableId"].(string)
|
Isnil("tableId", ok)
|
tmpinfo.PersonName,ok = source["personName"].(string)
|
Isnil("personName", ok)
|
tmpinfo.PersonPicUrl,ok = source["personPicUrl"].(string)
|
Isnil("personPicUrl", ok)
|
tmpinfo.PhoneNum,ok = source["phoneNum"].(string)
|
Isnil("phoneNum", ok)
|
tmpinfo.Sex,ok = source["sex"].(string)
|
Isnil("sex", ok)
|
tmpinfo.Idcard,ok = source["idCard"].(string)
|
Isnil("idCard", ok)
|
tmpinfo.MonitorLevel,ok = source["monitorLevel"].(string)
|
baseinfos = append(baseinfos, tmpinfo)
|
}
|
return baseinfos
|
}
|
|
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 EsReq(method string, url string, parama []byte) (buf []byte, err error) {
|
defer elapsed("page")()
|
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
|
}
|
|
// 计算时间
|
func elapsed(what string) func() {
|
start := time.Now()
|
return func() {
|
fmt.Printf("%s took %v\n", what, time.Since(start))
|
}
|
}
|
|
// 赋值时检测是否能够赋值
|
func Isnil(key string, ok bool){
|
if !ok {
|
fmt.Println(key, "is nil can not asign")
|
}
|
}
|