github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/toolbar/common/http_util.go (about)

     1  package common
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"io/ioutil"
     7  	"net/http"
     8  )
     9  
    10  func Get(url string, result interface{}) error {
    11  	client := &http.Client{}
    12  	resp, err := client.Get(url)
    13  	if err != nil {
    14  		return err
    15  	}
    16  
    17  	defer resp.Body.Close()
    18  	body, err := ioutil.ReadAll(resp.Body)
    19  	if err != nil {
    20  		return err
    21  	}
    22  
    23  	return json.Unmarshal(body, result)
    24  }
    25  
    26  func Post(url string, payload []byte, result interface{}) error {
    27  	req, err := http.NewRequest("POST", url, bytes.NewBuffer(payload))
    28  	if err != nil {
    29  		return err
    30  	}
    31  
    32  	req.Header.Set("Content-Type", "application/json")
    33  	client := &http.Client{}
    34  	resp, err := client.Do(req)
    35  	if err != nil {
    36  		return err
    37  	}
    38  
    39  	defer resp.Body.Close()
    40  	if result == nil {
    41  		return nil
    42  	}
    43  
    44  	body, err := ioutil.ReadAll(resp.Body)
    45  	if err != nil {
    46  		return err
    47  	}
    48  
    49  	return json.Unmarshal(body, result)
    50  }