github.com/cheng762/platon-go@v1.8.17-0.20190529111256-7deff2d7be26/cmd/ctool/core/http_util.go (about)

     1  package core
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"net/http"
     9  )
    10  
    11  func Send(params interface{}, action string) (string, error) {
    12  	param := JsonParam{
    13  		Jsonrpc: "2.0",
    14  		Method:  action,
    15  		Params:  params,
    16  		Id:      1,
    17  	}
    18  	resp, err := HttpPost(param)
    19  	if err != nil {
    20  		panic(fmt.Sprintf("send http post error .\n %s" + err.Error()))
    21  	}
    22  
    23  	return resp, err
    24  }
    25  
    26  func HttpPost(param JsonParam) (string, error) {
    27  
    28  	client := &http.Client{}
    29  	req, _ := json.Marshal(param)
    30  	reqNew := bytes.NewBuffer(req)
    31  
    32  	//fmt.Println(string(reqNew.Bytes()))
    33  
    34  	request, _ := http.NewRequest("POST", config.Url, reqNew)
    35  	request.Header.Set("Content-type", "application/json")
    36  	response, err := client.Do(request)
    37  	if response == nil && err != nil {
    38  		panic(fmt.Sprintf("no response from node,%s", err.Error()))
    39  	}
    40  	if err == nil && response.StatusCode == 200 {
    41  		body, _ := ioutil.ReadAll(response.Body)
    42  		return string(body), nil
    43  	} else {
    44  		panic(fmt.Sprintf("http response status :%s", response.Status))
    45  	}
    46  	return "", err
    47  }
    48  
    49  func parseResponse(r string) *Response {
    50  	var resp = Response{}
    51  	err := json.Unmarshal([]byte(r), &resp)
    52  
    53  	if err != nil {
    54  		panic(fmt.Sprintf("parse result error ! error:%s \n", err.Error()))
    55  	}
    56  
    57  	if resp.Error.Code != 0 {
    58  		panic(fmt.Sprintf("send transaction error ,error:%v \n", resp.Error.Message))
    59  	}
    60  	return &resp
    61  }