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.

133 lines
3.4 KiB

10 years ago
  1. // Commons for HTTP handling
  2. package rpc
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "net/url"
  8. "runtime/debug"
  9. "strings"
  10. "time"
  11. "github.com/tendermint/tendermint/alert"
  12. . "github.com/tendermint/tendermint/common"
  13. )
  14. type APIStatus string
  15. const (
  16. API_OK APIStatus = "OK"
  17. API_ERROR APIStatus = "ERROR"
  18. API_INVALID_PARAM APIStatus = "INVALID_PARAM"
  19. API_UNAUTHORIZED APIStatus = "UNAUTHORIZED"
  20. API_REDIRECT APIStatus = "REDIRECT"
  21. )
  22. type APIResponse struct {
  23. Status APIStatus `json:"status"`
  24. Data interface{} `json:"data"`
  25. }
  26. func (res APIResponse) Error() string {
  27. return fmt.Sprintf("Status(%v) %v", res.Status, res.Data)
  28. }
  29. // Throws a panic which the RecoverAndLogHandler catches.
  30. func ReturnJSON(status APIStatus, data interface{}) {
  31. res := APIResponse{}
  32. res.Status = status
  33. res.Data = data
  34. panic(res)
  35. }
  36. // Wraps an HTTP handler, adding error logging.
  37. //
  38. // If the inner function panics, the outer function recovers, logs, sends an
  39. // HTTP 500 error response.
  40. func RecoverAndLogHandler(handler http.Handler) http.Handler {
  41. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  42. // Wrap the ResponseWriter to remember the status
  43. rww := &ResponseWriterWrapper{-1, w}
  44. begin := time.Now()
  45. // Common headers
  46. origin := r.Header.Get("Origin")
  47. originUrl, err := url.Parse(origin)
  48. if err == nil {
  49. originHost := strings.Split(originUrl.Host, ":")[0]
  50. if strings.HasSuffix(originHost, ".ftnox.com") {
  51. rww.Header().Set("Access-Control-Allow-Origin", origin)
  52. rww.Header().Set("Access-Control-Allow-Credentials", "true")
  53. rww.Header().Set("Access-Control-Expose-Headers", "X-Server-Time")
  54. }
  55. }
  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 APIResponse,
  63. if res, ok := e.(APIResponse); ok {
  64. resJSON, err := json.Marshal(res)
  65. if err != nil {
  66. panic(err)
  67. }
  68. rww.Header().Set("Content-Type", "application/json")
  69. switch res.Status {
  70. case API_OK:
  71. rww.WriteHeader(200)
  72. case API_ERROR:
  73. rww.WriteHeader(400)
  74. case API_UNAUTHORIZED:
  75. rww.WriteHeader(401)
  76. case API_INVALID_PARAM:
  77. rww.WriteHeader(420)
  78. case API_REDIRECT:
  79. rww.WriteHeader(430)
  80. default:
  81. rww.WriteHeader(440)
  82. }
  83. rww.Write(resJSON)
  84. } else {
  85. // For the rest,
  86. rww.WriteHeader(http.StatusInternalServerError)
  87. rww.Write([]byte("Internal Server Error"))
  88. log.Error("Panic in HTTP handler", "error", e, "stack", debug.Stack())
  89. }
  90. }
  91. // Finally, log.
  92. durationMS := time.Since(begin).Nanoseconds() / 1000000
  93. if rww.Status == -1 {
  94. rww.Status = 200
  95. }
  96. log.Debug(Fmt("%s %s %v %v %s", r.RemoteAddr, r.Method, rww.Status, durationMS, r.URL))
  97. }()
  98. handler.ServeHTTP(rww, r)
  99. })
  100. }
  101. // Remember the status for logging
  102. type ResponseWriterWrapper struct {
  103. Status int
  104. http.ResponseWriter
  105. }
  106. func (w *ResponseWriterWrapper) WriteHeader(status int) {
  107. w.Status = status
  108. w.ResponseWriter.WriteHeader(status)
  109. }
  110. // Stick it as a deferred statement in gouroutines to prevent the program from crashing.
  111. func Recover(daemonName string) {
  112. if e := recover(); e != nil {
  113. stack := string(debug.Stack())
  114. errorString := fmt.Sprintf("[%s] %s\n%s", daemonName, e, stack)
  115. alert.Alert(errorString)
  116. }
  117. }