github.com/jeffallen/go-ethereum@v1.1.4-0.20150910155051-571d3236c49c/rpc/comms/inproc.go (about)

     1  // Copyright 2015 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package comms
    18  
    19  import (
    20  	"fmt"
    21  
    22  	"github.com/ethereum/go-ethereum/rpc/codec"
    23  	"github.com/ethereum/go-ethereum/rpc/shared"
    24  )
    25  
    26  type InProcClient struct {
    27  	api         shared.EthereumApi
    28  	codec       codec.Codec
    29  	lastId      interface{}
    30  	lastJsonrpc string
    31  	lastErr     error
    32  	lastRes     interface{}
    33  }
    34  
    35  // Create a new in process client
    36  func NewInProcClient(codec codec.Codec) *InProcClient {
    37  	return &InProcClient{
    38  		codec: codec,
    39  	}
    40  }
    41  
    42  func (self *InProcClient) Close() {
    43  	// do nothing
    44  }
    45  
    46  // Need to setup api support
    47  func (self *InProcClient) Initialize(offeredApi shared.EthereumApi) {
    48  	self.api = offeredApi
    49  }
    50  
    51  func (self *InProcClient) Send(req interface{}) error {
    52  	if r, ok := req.(*shared.Request); ok {
    53  		self.lastId = r.Id
    54  		self.lastJsonrpc = r.Jsonrpc
    55  		self.lastRes, self.lastErr = self.api.Execute(r)
    56  		return self.lastErr
    57  	}
    58  
    59  	return fmt.Errorf("Invalid request (%T)", req)
    60  }
    61  
    62  func (self *InProcClient) Recv() (interface{}, error) {
    63  	return *shared.NewRpcResponse(self.lastId, self.lastJsonrpc, self.lastRes, self.lastErr), nil
    64  }
    65  
    66  func (self *InProcClient) SupportedModules() (map[string]string, error) {
    67  	req := shared.Request{
    68  		Id:      1,
    69  		Jsonrpc: "2.0",
    70  		Method:  "modules",
    71  	}
    72  
    73  	if res, err := self.api.Execute(&req); err == nil {
    74  		if result, ok := res.(map[string]string); ok {
    75  			return result, nil
    76  		}
    77  	} else {
    78  		return nil, err
    79  	}
    80  
    81  	return nil, fmt.Errorf("Invalid response")
    82  }