http.go 5.0 KB

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