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.

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