You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

125 lines
3.6 KiB

  1. // Commons for HTTP handling
  2. package rpcserver
  3. import (
  4. "bufio"
  5. "encoding/json"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "runtime/debug"
  10. "strings"
  11. "time"
  12. "github.com/pkg/errors"
  13. types "github.com/tendermint/go-rpc/types"
  14. )
  15. func StartHTTPServer(listenAddr string, handler http.Handler) (listener net.Listener, err error) {
  16. // listenAddr should be fully formed including tcp:// or unix:// prefix
  17. var proto, addr string
  18. parts := strings.SplitN(listenAddr, "://", 2)
  19. if len(parts) != 2 {
  20. log.Warn("WARNING (go-rpc): Please use fully formed listening addresses, including the tcp:// or unix:// prefix")
  21. // we used to allow addrs without tcp/unix prefix by checking for a colon
  22. // TODO: Deprecate
  23. proto = types.SocketType(listenAddr)
  24. addr = listenAddr
  25. // return nil, errors.Errorf("Invalid listener address %s", lisenAddr)
  26. } else {
  27. proto, addr = parts[0], parts[1]
  28. }
  29. log.Notice(fmt.Sprintf("Starting RPC HTTP server on %s socket %v", proto, addr))
  30. listener, err = net.Listen(proto, addr)
  31. if err != nil {
  32. return nil, errors.Errorf("Failed to listen to %v: %v", listenAddr, err)
  33. }
  34. go func() {
  35. res := http.Serve(
  36. listener,
  37. RecoverAndLogHandler(handler),
  38. )
  39. log.Crit("RPC HTTP server stopped", "result", res)
  40. }()
  41. return listener, nil
  42. }
  43. func WriteRPCResponseHTTP(w http.ResponseWriter, res types.RPCResponse) {
  44. // jsonBytes := wire.JSONBytesPretty(res)
  45. jsonBytes, err := json.Marshal(res)
  46. if err != nil {
  47. panic(err)
  48. }
  49. w.Header().Set("Content-Type", "application/json")
  50. w.WriteHeader(200)
  51. w.Write(jsonBytes)
  52. }
  53. //-----------------------------------------------------------------------------
  54. // Wraps an HTTP handler, adding error logging.
  55. // If the inner function panics, the outer function recovers, logs, sends an
  56. // HTTP 500 error response.
  57. func RecoverAndLogHandler(handler http.Handler) http.Handler {
  58. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  59. // Wrap the ResponseWriter to remember the status
  60. rww := &ResponseWriterWrapper{-1, w}
  61. begin := time.Now()
  62. // Common headers
  63. origin := r.Header.Get("Origin")
  64. rww.Header().Set("Access-Control-Allow-Origin", origin)
  65. rww.Header().Set("Access-Control-Allow-Credentials", "true")
  66. rww.Header().Set("Access-Control-Expose-Headers", "X-Server-Time")
  67. rww.Header().Set("X-Server-Time", fmt.Sprintf("%v", begin.Unix()))
  68. defer func() {
  69. // Send a 500 error if a panic happens during a handler.
  70. // Without this, Chrome & Firefox were retrying aborted ajax requests,
  71. // at least to my localhost.
  72. if e := recover(); e != nil {
  73. // If RPCResponse
  74. if res, ok := e.(types.RPCResponse); ok {
  75. WriteRPCResponseHTTP(rww, res)
  76. } else {
  77. // For the rest,
  78. log.Error("Panic in RPC HTTP handler", "error", e, "stack", string(debug.Stack()))
  79. rww.WriteHeader(http.StatusInternalServerError)
  80. WriteRPCResponseHTTP(rww, types.NewRPCResponse("", nil, fmt.Sprintf("Internal Server Error: %v", e)))
  81. }
  82. }
  83. // Finally, log.
  84. durationMS := time.Since(begin).Nanoseconds() / 1000000
  85. if rww.Status == -1 {
  86. rww.Status = 200
  87. }
  88. log.Info("Served RPC HTTP response",
  89. "method", r.Method, "url", r.URL,
  90. "status", rww.Status, "duration", durationMS,
  91. "remoteAddr", r.RemoteAddr,
  92. )
  93. }()
  94. handler.ServeHTTP(rww, r)
  95. })
  96. }
  97. // Remember the status for logging
  98. type ResponseWriterWrapper struct {
  99. Status int
  100. http.ResponseWriter
  101. }
  102. func (w *ResponseWriterWrapper) WriteHeader(status int) {
  103. w.Status = status
  104. w.ResponseWriter.WriteHeader(status)
  105. }
  106. // implements http.Hijacker
  107. func (w *ResponseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  108. return w.ResponseWriter.(http.Hijacker).Hijack()
  109. }