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.

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