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.

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