OSDN Git Service

5222373dc60a623ac90ab20391cba8e8c191ed01
[bytom/bytom-spv.git] / util / util.go
1 package util
2
3 import (
4         "context"
5
6         "github.com/bytom/api"
7         "github.com/bytom/blockchain/rpc"
8         "github.com/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://localhost:9888")
28 )
29
30 // Wraper rpc's client
31 func MustRPCClient() *rpc.Client {
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 = &api.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 api.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 }