From e12bca22ef82aa5a2df0448a4715b1a948604156 Mon Sep 17 00:00:00 2001
From: sunty <1172534965@qq.com>
Date: 星期二, 07 四月 2020 14:57:38 +0800
Subject: [PATCH] first commit

---
 util/util.go |  100 ++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 100 insertions(+), 0 deletions(-)

diff --git a/util/util.go b/util/util.go
new file mode 100644
index 0000000..bf2337a
--- /dev/null
+++ b/util/util.go
@@ -0,0 +1,100 @@
+package util
+
+import (
+	"bytes"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io/ioutil"
+	"net/http"
+	"os/exec"
+	"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()
+}
+
+//瑙f瀽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
+}
+
+//瑙f瀽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
+}
+
+//瑙f瀽鏇存柊
+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{}")
+	}
+
+	middle, ok := out["updated"].(float64)
+	if !ok {
+		return -1, errors.New("first total change error!")
+	}
+	total = int(middle)
+	return total, nil
+}

--
Gitblit v1.8.0