github.com/turingchain2020/turingchain@v1.1.21/rpc/jsonclient/rpc_ctx.go (about) 1 // Copyright Turing Corp. 2018 All Rights Reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package jsonclient 6 7 import ( 8 "encoding/json" 9 "fmt" 10 "os" 11 ) 12 13 // RPCCtx rpc ctx interface 14 // TODO: SetPostRunCb() 15 type RPCCtx struct { 16 Addr string 17 Method string 18 Params interface{} 19 Res interface{} 20 cb Callback 21 } 22 23 // Callback a callback function 24 type Callback func(res interface{}) (interface{}, error) 25 26 // NewRPCCtx produce a object of rpcctx 27 func NewRPCCtx(laddr, method string, params, res interface{}) *RPCCtx { 28 return &RPCCtx{ 29 Addr: laddr, 30 Method: method, 31 Params: params, 32 Res: res, 33 } 34 } 35 36 // SetResultCb rpcctx callback 37 func (c *RPCCtx) SetResultCb(cb Callback) { 38 c.cb = cb 39 } 40 41 // RunResult format rpc result 42 func (c *RPCCtx) RunResult() (interface{}, error) { 43 rpc, err := NewJSONClient(c.Addr) 44 if err != nil { 45 return nil, err 46 } 47 48 err = rpc.Call(c.Method, c.Params, c.Res) 49 if err != nil { 50 return nil, err 51 } 52 // maybe format rpc result 53 var result interface{} 54 if c.cb != nil { 55 result, err = c.cb(c.Res) 56 if err != nil { 57 return nil, err 58 } 59 } else { 60 result = c.Res 61 } 62 return result, nil 63 } 64 65 // Run rpcctx to runresult 66 func (c *RPCCtx) Run() { 67 result, err := c.RunResult() 68 if err != nil { 69 fmt.Fprintln(os.Stderr, err) 70 return 71 } 72 data, err := json.MarshalIndent(result, "", " ") 73 if err != nil { 74 fmt.Fprintln(os.Stderr, err) 75 return 76 } 77 fmt.Println(string(data)) 78 } 79 80 // RunWithoutMarshal return source result of string 81 func (c *RPCCtx) RunWithoutMarshal() { 82 var res string 83 rpc, err := NewJSONClient(c.Addr) 84 if err != nil { 85 fmt.Fprintln(os.Stderr, err) 86 return 87 } 88 89 err = rpc.Call(c.Method, c.Params, &res) 90 if err != nil { 91 fmt.Fprintln(os.Stderr, err) 92 return 93 } 94 95 fmt.Println(res) 96 }