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.

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