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.

98 lines
2.7 KiB

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