http.go 4.2 KB

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