OSDN Git Service

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