github.com/Bytom/bytom@v1.1.2-0.20210127130405-ae40204c0b09/util/util.go (about)

     1  package util
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/bytom/bytom/api"
     7  	"github.com/bytom/bytom/blockchain/rpc"
     8  	"github.com/bytom/bytom/env"
     9  	jww "github.com/spf13/jwalterweatherman"
    10  )
    11  
    12  const (
    13  	// Success indicates the rpc calling is successful.
    14  	Success = iota
    15  	// ErrLocalExe indicates error occurs before the rpc calling.
    16  	ErrLocalExe
    17  	// ErrConnect indicates error occurs connecting to the bytomd, e.g.,
    18  	// bytomd can't parse the received arguments.
    19  	ErrConnect
    20  	// ErrLocalParse indicates error occurs locally when parsing the response.
    21  	ErrLocalParse
    22  	// ErrRemote indicates error occurs in bytomd.
    23  	ErrRemote
    24  )
    25  
    26  var (
    27  	coreURL = env.String("BYTOM_URL", "http://127.0.0.1:9888")
    28  )
    29  
    30  // Wraper rpc's client
    31  func MustRPCClient() *rpc.Client {
    32  	env.Parse()
    33  	return &rpc.Client{BaseURL: *coreURL}
    34  }
    35  
    36  // Wrapper rpc call api.
    37  func ClientCall(path string, req ...interface{}) (interface{}, int) {
    38  
    39  	var response = &api.Response{}
    40  	var request interface{}
    41  
    42  	if req != nil {
    43  		request = req[0]
    44  	}
    45  
    46  	client := MustRPCClient()
    47  	client.Call(context.Background(), path, request, response)
    48  
    49  	switch response.Status {
    50  	case api.FAIL:
    51  		jww.ERROR.Println(response.Msg)
    52  		return nil, ErrRemote
    53  	case "":
    54  		jww.ERROR.Println("Unable to connect to the bytomd")
    55  		return nil, ErrConnect
    56  	}
    57  
    58  	return response.Data, Success
    59  }