github.com/digdeepmining/go-atheios@v1.5.13-0.20180902133602-d5687a2e6f43/rpc/http.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 rpc
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/json"
    22  	"fmt"
    23  	"io"
    24  	"io/ioutil"
    25  	"net"
    26  	"net/http"
    27  	"strings"
    28  	"sync"
    29  	"time"
    30  
    31  	"github.com/rs/cors"
    32  	"golang.org/x/net/context"
    33  )
    34  
    35  const (
    36  	maxHTTPRequestContentLength = 1024 * 128
    37  )
    38  
    39  var nullAddr, _ = net.ResolveTCPAddr("tcp", "127.0.0.1:0")
    40  
    41  type httpConn struct {
    42  	client    *http.Client
    43  	req       *http.Request
    44  	closeOnce sync.Once
    45  	closed    chan struct{}
    46  }
    47  
    48  // httpConn is treated specially by Client.
    49  func (hc *httpConn) LocalAddr() net.Addr              { return nullAddr }
    50  func (hc *httpConn) RemoteAddr() net.Addr             { return nullAddr }
    51  func (hc *httpConn) SetReadDeadline(time.Time) error  { return nil }
    52  func (hc *httpConn) SetWriteDeadline(time.Time) error { return nil }
    53  func (hc *httpConn) SetDeadline(time.Time) error      { return nil }
    54  func (hc *httpConn) Write([]byte) (int, error)        { panic("Write called") }
    55  
    56  func (hc *httpConn) Read(b []byte) (int, error) {
    57  	<-hc.closed
    58  	return 0, io.EOF
    59  }
    60  
    61  func (hc *httpConn) Close() error {
    62  	hc.closeOnce.Do(func() { close(hc.closed) })
    63  	return nil
    64  }
    65  
    66  // DialHTTP creates a new RPC clients that connection to an RPC server over HTTP.
    67  func DialHTTP(endpoint string) (*Client, error) {
    68  	req, err := http.NewRequest("POST", endpoint, nil)
    69  	if err != nil {
    70  		return nil, err
    71  	}
    72  	req.Header.Set("Content-Type", "application/json")
    73  	req.Header.Set("Accept", "application/json")
    74  
    75  	initctx := context.Background()
    76  	return newClient(initctx, func(context.Context) (net.Conn, error) {
    77  		return &httpConn{client: new(http.Client), req: req, closed: make(chan struct{})}, nil
    78  	})
    79  }
    80  
    81  func (c *Client) sendHTTP(ctx context.Context, op *requestOp, msg interface{}) error {
    82  	hc := c.writeConn.(*httpConn)
    83  	respBody, err := hc.doRequest(ctx, msg)
    84  	if err != nil {
    85  		return err
    86  	}
    87  	defer respBody.Close()
    88  	var respmsg jsonrpcMessage
    89  	if err := json.NewDecoder(respBody).Decode(&respmsg); err != nil {
    90  		return err
    91  	}
    92  	op.resp <- &respmsg
    93  	return nil
    94  }
    95  
    96  func (c *Client) sendBatchHTTP(ctx context.Context, op *requestOp, msgs []*jsonrpcMessage) error {
    97  	hc := c.writeConn.(*httpConn)
    98  	respBody, err := hc.doRequest(ctx, msgs)
    99  	if err != nil {
   100  		return err
   101  	}
   102  	defer respBody.Close()
   103  	var respmsgs []jsonrpcMessage
   104  	if err := json.NewDecoder(respBody).Decode(&respmsgs); err != nil {
   105  		return err
   106  	}
   107  	for _, respmsg := range respmsgs {
   108  		op.resp <- &respmsg
   109  	}
   110  	return nil
   111  }
   112  
   113  func (hc *httpConn) doRequest(ctx context.Context, msg interface{}) (io.ReadCloser, error) {
   114  	body, err := json.Marshal(msg)
   115  	if err != nil {
   116  		return nil, err
   117  	}
   118  	client, req := requestWithContext(hc.client, hc.req, ctx)
   119  	req.Body = ioutil.NopCloser(bytes.NewReader(body))
   120  	req.ContentLength = int64(len(body))
   121  
   122  	resp, err := client.Do(req)
   123  	if err != nil {
   124  		return nil, err
   125  	}
   126  	return resp.Body, nil
   127  }
   128  
   129  // httpReadWriteNopCloser wraps a io.Reader and io.Writer with a NOP Close method.
   130  type httpReadWriteNopCloser struct {
   131  	io.Reader
   132  	io.Writer
   133  }
   134  
   135  // Close does nothing and returns always nil
   136  func (t *httpReadWriteNopCloser) Close() error {
   137  	return nil
   138  }
   139  
   140  // NewHTTPServer creates a new HTTP RPC server around an API provider.
   141  //
   142  // Deprecated: Server implements http.Handler
   143  func NewHTTPServer(corsString string, srv *Server) *http.Server {
   144  	return &http.Server{Handler: newCorsHandler(srv, corsString)}
   145  }
   146  
   147  // ServeHTTP serves JSON-RPC requests over HTTP.
   148  func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
   149  	if r.ContentLength > maxHTTPRequestContentLength {
   150  		http.Error(w,
   151  			fmt.Sprintf("content length too large (%d>%d)", r.ContentLength, maxHTTPRequestContentLength),
   152  			http.StatusRequestEntityTooLarge)
   153  		return
   154  	}
   155  	w.Header().Set("content-type", "application/json")
   156  
   157  	// create a codec that reads direct from the request body until
   158  	// EOF and writes the response to w and order the server to process
   159  	// a single request.
   160  	codec := NewJSONCodec(&httpReadWriteNopCloser{r.Body, w})
   161  	defer codec.Close()
   162  	srv.ServeSingleRequest(codec, OptionMethodInvocation)
   163  }
   164  
   165  func newCorsHandler(srv *Server, corsString string) http.Handler {
   166  	var allowedOrigins []string
   167  	for _, domain := range strings.Split(corsString, ",") {
   168  		allowedOrigins = append(allowedOrigins, strings.TrimSpace(domain))
   169  	}
   170  	c := cors.New(cors.Options{
   171  		AllowedOrigins: allowedOrigins,
   172  		AllowedMethods: []string{"POST", "GET"},
   173  		MaxAge:         600,
   174  	})
   175  	return c.Handler(srv)
   176  }