package util import ( "bytes" "encoding/json" "errors" "fmt" "github.com/gin-gonic/gin" "io/ioutil" "net/http" "os/exec" "swfs/code" "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() } //解析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 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 } // ResponseFormat 返回数据格式化 func ResponseFormat(c *gin.Context, respStatus *code.Code, data interface{}) { if respStatus == nil { respStatus = code.RequestParamError } c.JSON(respStatus.Status, gin.H{ "code": respStatus.Status, "success": respStatus.Success, "msg": respStatus.Message, "data": data, }) return }