tendermint/rpc/http_server.go

118 lines
3.3 KiB
Go
Raw Normal View History

2015-01-11 17:10:34 -08:00
// Commons for HTTP handling
2014-11-27 04:04:07 -08:00
package rpc
import (
2015-01-11 17:10:34 -08:00
"bytes"
"fmt"
2014-11-27 04:04:07 -08:00
"net/http"
2015-01-11 17:10:34 -08:00
"runtime/debug"
"time"
2014-11-27 04:04:07 -08:00
2015-03-30 22:50:27 -07:00
"github.com/tendermint/tendermint2/alert"
"github.com/tendermint/tendermint2/binary"
. "github.com/tendermint/tendermint2/common"
"github.com/tendermint/tendermint2/config"
2014-11-27 04:04:07 -08:00
)
func StartHTTPServer() {
2015-01-11 17:10:34 -08:00
initHandlers()
2014-11-27 04:04:07 -08:00
2015-03-16 23:16:26 -07:00
log.Info(Fmt("Starting RPC HTTP server on %s", config.App().GetString("RPC.HTTP.ListenAddr")))
2014-11-27 04:04:07 -08:00
go func() {
2015-03-16 23:16:26 -07:00
log.Crit("RPC HTTPServer stopped", "result", http.ListenAndServe(config.App().GetString("RPC.HTTP.ListenAddr"), RecoverAndLogHandler(http.DefaultServeMux)))
2014-11-27 04:04:07 -08:00
}()
}
2015-01-11 17:10:34 -08:00
2015-04-01 04:58:33 -07:00
func WriteRPCResponse(w http.ResponseWriter, res RPCResponse) {
2015-01-11 17:10:34 -08:00
buf, n, err := new(bytes.Buffer), new(int64), new(error)
binary.WriteJSON(res, buf, n, err)
if *err != nil {
2015-04-01 04:58:33 -07:00
log.Warn("Failed to write JSON RPCResponse", "error", err)
2015-01-11 17:10:34 -08:00
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
w.Write(buf.Bytes())
}
2015-04-01 01:46:41 -07:00
//-----------------------------------------------------------------------------
2015-01-11 17:10:34 -08:00
// Wraps an HTTP handler, adding error logging.
//
// If the inner function panics, the outer function recovers, logs, sends an
// HTTP 500 error response.
func RecoverAndLogHandler(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Wrap the ResponseWriter to remember the status
rww := &ResponseWriterWrapper{-1, w}
begin := time.Now()
// Common headers
rww.Header().Set("Access-Control-Allow-Origin", "*")
/*
origin := r.Header.Get("Origin")
originUrl, err := url.Parse(origin)
if err == nil {
originHost := strings.Split(originUrl.Host, ":")[0]
if strings.HasSuffix(originHost, ".tendermint.com") {
rww.Header().Set("Access-Control-Allow-Origin", origin)
rww.Header().Set("Access-Control-Allow-Credentials", "true")
rww.Header().Set("Access-Control-Expose-Headers", "X-Server-Time")
}
}
*/
rww.Header().Set("X-Server-Time", fmt.Sprintf("%v", begin.Unix()))
defer func() {
// Send a 500 error if a panic happens during a handler.
// Without this, Chrome & Firefox were retrying aborted ajax requests,
// at least to my localhost.
if e := recover(); e != nil {
2015-04-01 04:58:33 -07:00
// If RPCResponse
if res, ok := e.(RPCResponse); ok {
WriteRPCResponse(rww, res)
2015-01-11 17:10:34 -08:00
} else {
// For the rest,
rww.WriteHeader(http.StatusInternalServerError)
rww.Write([]byte("Internal Server Error"))
log.Error("Panic in HTTP handler", "error", e, "stack", string(debug.Stack()))
}
}
// Finally, log.
durationMS := time.Since(begin).Nanoseconds() / 1000000
if rww.Status == -1 {
rww.Status = 200
}
log.Debug("Served HTTP response",
"method", r.Method, "url", r.URL,
"status", rww.Status, "duration", durationMS,
"remoteAddr", r.RemoteAddr,
)
}()
handler.ServeHTTP(rww, r)
})
}
// Remember the status for logging
type ResponseWriterWrapper struct {
Status int
http.ResponseWriter
}
func (w *ResponseWriterWrapper) WriteHeader(status int) {
w.Status = status
w.ResponseWriter.WriteHeader(status)
}
// Stick it as a deferred statement in gouroutines to prevent the program from crashing.
func Recover(daemonName string) {
if e := recover(); e != nil {
stack := string(debug.Stack())
errorString := fmt.Sprintf("[%s] %s\n%s", daemonName, e, stack)
alert.Alert(errorString)
}
}