aboutsummaryrefslogtreecommitdiffstats
path: root/rpc/http.go
blob: 44e2ad6ab39146405ee1878b0aeadb2c8e48fd57 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package rpc

import (
    "net/http"

    "github.com/ethereum/go-ethereum/logger"
    "github.com/ethereum/go-ethereum/xeth"
)

var rpchttplogger = logger.NewLogger("RPC-HTTP")

// JSONRPC returns a handler that implements the Ethereum JSON-RPC API.
func JSONRPC(pipe *xeth.XEth, dataDir string) http.Handler {
    var json JsonWrapper
    const jsonrpcver = "2.0"
    api := NewEthereumApi(pipe, dataDir)

    return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
        w.Header().Set("Access-Control-Allow-Origin", "*")

        rpchttplogger.DebugDetailln("Handling request")

        reqParsed, reqerr := json.ParseRequestBody(req)
        if reqerr != nil {
            jsonerr := &RpcErrorObject{-32700, "Error: Could not parse request"}
            json.Send(w, &RpcErrorResponse{JsonRpc: jsonrpcver, ID: nil, Error: jsonerr})
            return
        }

        var response interface{}
        reserr := api.GetRequestReply(&reqParsed, &response)
        if reserr != nil {
            rpchttplogger.Warnln(reserr)
            jsonerr := &RpcErrorObject{-32603, reserr.Error()}
            json.Send(w, &RpcErrorResponse{JsonRpc: jsonrpcver, ID: reqParsed.ID, Error: jsonerr})
            return
        }

        rpchttplogger.DebugDetailf("Generated response: %T %s", response, response)
        json.Send(w, &RpcSuccessResponse{JsonRpc: jsonrpcver, ID: reqParsed.ID, Result: response})
    })
}