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

     1  package apinode
     2  
     3  import (
     4  	"encoding/json"
     5  
     6  	"github.com/bytom/bytom/errors"
     7  	"github.com/bytom/bytom/toolbar/common"
     8  )
     9  
    10  // Node can invoke the api which provide by the full node server
    11  type Node struct {
    12  	hostPort string
    13  }
    14  
    15  // NewNode create a api client with target server
    16  func NewNode(hostPort string) *Node {
    17  	return &Node{hostPort: hostPort}
    18  }
    19  
    20  type response struct {
    21  	Status    string          `json:"status"`
    22  	Data      json.RawMessage `json:"data"`
    23  	ErrDetail string          `json:"error_detail"`
    24  }
    25  
    26  func (n *Node) request(path string, payload []byte, respData interface{}) error {
    27  	resp := &response{}
    28  	if err := common.Post(n.hostPort+path, payload, resp); err != nil {
    29  		return err
    30  	}
    31  
    32  	if resp.Status != "success" {
    33  		return errors.New(resp.ErrDetail)
    34  	}
    35  
    36  	if resp.Data == nil {
    37  		return nil
    38  	}
    39  
    40  	return json.Unmarshal(resp.Data, respData)
    41  }