github.com/ethereumproject/go-ethereum@v5.5.2+incompatible/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/http"
    26  	"strings"
    27  
    28  	"github.com/rs/cors"
    29  )
    30  
    31  const (
    32  	maxHTTPRequestContentLength = 1024 * 128
    33  )
    34  
    35  // httpClient connects to a geth RPC server over HTTP.
    36  type httpClient struct {
    37  	endpoint   string      // HTTP-RPC server endpoint
    38  	httpClient http.Client // reuse connection
    39  	lastRes    []byte      // HTTP requests are synchronous, store last response
    40  }
    41  
    42  // Send will serialize the given msg to JSON and sends it to the RPC server.
    43  // Since HTTP is synchronous the response is stored until Recv is called.
    44  func (client *httpClient) Send(msg interface{}) error {
    45  	var body []byte
    46  	var err error
    47  
    48  	client.lastRes = nil
    49  	if body, err = json.Marshal(msg); err != nil {
    50  		return err
    51  	}
    52  
    53  	resp, err := client.httpClient.Post(client.endpoint, "application/json", bytes.NewReader(body))
    54  	if err != nil {
    55  		return err
    56  	}
    57  
    58  	defer resp.Body.Close()
    59  	if resp.StatusCode == http.StatusOK {
    60  		client.lastRes, err = ioutil.ReadAll(resp.Body)
    61  		return err
    62  	}
    63  
    64  	return fmt.Errorf("request failed: %s", resp.Status)
    65  }
    66  
    67  // Recv will try to deserialize the last received response into the given msg.
    68  func (client *httpClient) Recv(msg interface{}) error {
    69  	return json.Unmarshal(client.lastRes, &msg)
    70  }
    71  
    72  // Close is not necessary for httpClient
    73  func (client *httpClient) Close() {
    74  }
    75  
    76  // SupportedModules will return the collection of offered RPC modules.
    77  func (client *httpClient) SupportedModules() (map[string]string, error) {
    78  	return SupportedModules(client)
    79  }
    80  
    81  // httpReadWriteNopCloser wraps a io.Reader and io.Writer with a NOP Close method.
    82  type httpReadWriteNopCloser struct {
    83  	io.Reader
    84  	io.Writer
    85  }
    86  
    87  // Close does nothing and returns always nil
    88  func (t *httpReadWriteNopCloser) Close() error {
    89  	return nil
    90  }
    91  
    92  // newJSONHTTPHandler creates a HTTP handler that will parse incoming JSON requests,
    93  // send the request to the given API provider and sends the response back to the caller.
    94  func newJSONHTTPHandler(srv *Server) http.HandlerFunc {
    95  	return func(w http.ResponseWriter, r *http.Request) {
    96  		if r.ContentLength > maxHTTPRequestContentLength {
    97  			http.Error(w,
    98  				fmt.Sprintf("content length too large (%d>%d)", r.ContentLength, maxHTTPRequestContentLength),
    99  				http.StatusRequestEntityTooLarge)
   100  			return
   101  		}
   102  
   103  		w.Header().Set("content-type", "application/json")
   104  
   105  		// create a codec that reads direct from the request body until
   106  		// EOF and writes the response to w and order the server to process
   107  		// a single request.
   108  		codec := NewJSONCodec(&httpReadWriteNopCloser{r.Body, w})
   109  		defer codec.Close()
   110  		srv.ServeSingleRequest(codec, OptionMethodInvocation)
   111  	}
   112  }
   113  
   114  // NewHTTPServer creates a new HTTP RPC server around an API provider.
   115  func NewHTTPServer(corsString string, srv *Server) *http.Server {
   116  	var allowedOrigins []string
   117  	for _, domain := range strings.Split(corsString, ",") {
   118  		allowedOrigins = append(allowedOrigins, strings.TrimSpace(domain))
   119  	}
   120  
   121  	c := cors.New(cors.Options{
   122  		AllowedOrigins: allowedOrigins,
   123  		AllowedMethods: []string{"POST", "GET"},
   124  	})
   125  
   126  	handler := c.Handler(newJSONHTTPHandler(srv))
   127  
   128  	return &http.Server{
   129  		Handler: handler,
   130  	}
   131  }