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.

105 lines
2.9 KiB

10 years ago
10 years ago
  1. // Commons for HTTP handling
  2. package rpc
  3. import (
  4. "bytes"
  5. "fmt"
  6. "net/http"
  7. "runtime/debug"
  8. "time"
  9. "github.com/tendermint/tendermint/binary"
  10. . "github.com/tendermint/tendermint/common"
  11. "github.com/tendermint/tendermint/events"
  12. )
  13. func StartHTTPServer(listenAddr string, funcMap map[string]*RPCFunc, evsw *events.EventSwitch) {
  14. log.Info(Fmt("Starting RPC HTTP server on %s", listenAddr))
  15. mux := http.NewServeMux()
  16. RegisterRPCFuncs(mux, funcMap)
  17. if evsw != nil {
  18. RegisterEventsHandler(mux, evsw)
  19. }
  20. go func() {
  21. res := http.ListenAndServe(
  22. listenAddr,
  23. RecoverAndLogHandler(mux),
  24. )
  25. log.Crit("RPC HTTPServer stopped", "result", res)
  26. }()
  27. }
  28. func WriteRPCResponse(w http.ResponseWriter, res RPCResponse) {
  29. buf, n, err := new(bytes.Buffer), new(int64), new(error)
  30. binary.WriteJSON(res, buf, n, err)
  31. if *err != nil {
  32. log.Warn("Failed to write JSON RPCResponse", "error", err)
  33. }
  34. w.Header().Set("Content-Type", "application/json")
  35. w.WriteHeader(200)
  36. w.Write(buf.Bytes())
  37. }
  38. //-----------------------------------------------------------------------------
  39. // Wraps an HTTP handler, adding error logging.
  40. //
  41. // If the inner function panics, the outer function recovers, logs, sends an
  42. // HTTP 500 error response.
  43. func RecoverAndLogHandler(handler http.Handler) http.Handler {
  44. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  45. // Wrap the ResponseWriter to remember the status
  46. rww := &ResponseWriterWrapper{-1, w}
  47. begin := time.Now()
  48. // Common headers
  49. origin := r.Header.Get("Origin")
  50. rww.Header().Set("Access-Control-Allow-Origin", origin)
  51. rww.Header().Set("Access-Control-Allow-Credentials", "true")
  52. rww.Header().Set("Access-Control-Expose-Headers", "X-Server-Time")
  53. rww.Header().Set("X-Server-Time", fmt.Sprintf("%v", begin.Unix()))
  54. defer func() {
  55. // Send a 500 error if a panic happens during a handler.
  56. // Without this, Chrome & Firefox were retrying aborted ajax requests,
  57. // at least to my localhost.
  58. if e := recover(); e != nil {
  59. // If RPCResponse
  60. if res, ok := e.(RPCResponse); ok {
  61. WriteRPCResponse(rww, res)
  62. } else {
  63. // For the rest,
  64. log.Error("Panic in HTTP handler", "error", e, "stack", string(debug.Stack()))
  65. rww.WriteHeader(http.StatusInternalServerError)
  66. WriteRPCResponse(rww, NewRPCResponse(nil, Fmt("Internal Server Error: %v", e)))
  67. }
  68. }
  69. // Finally, log.
  70. durationMS := time.Since(begin).Nanoseconds() / 1000000
  71. if rww.Status == -1 {
  72. rww.Status = 200
  73. }
  74. log.Debug("Served HTTP response",
  75. "method", r.Method, "url", r.URL,
  76. "status", rww.Status, "duration", durationMS,
  77. "remoteAddr", r.RemoteAddr,
  78. )
  79. }()
  80. handler.ServeHTTP(rww, r)
  81. })
  82. }
  83. // Remember the status for logging
  84. type ResponseWriterWrapper struct {
  85. Status int
  86. http.ResponseWriter
  87. }
  88. func (w *ResponseWriterWrapper) WriteHeader(status int) {
  89. w.Status = status
  90. w.ResponseWriter.WriteHeader(status)
  91. }