aboutsummaryrefslogtreecommitdiffstats
path: root/rpc/comms/http.go
blob: 04630d9375aa4b5f61d67e888331f961ca36fb7c (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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package comms

import (
    "fmt"
    "net/http"
    "strings"

    "github.com/ethereum/go-ethereum/logger"
    "github.com/ethereum/go-ethereum/logger/glog"
    "github.com/ethereum/go-ethereum/rpc/api"
    "github.com/ethereum/go-ethereum/rpc/codec"
    "github.com/rs/cors"
)

var (
    // main HTTP rpc listener
    httpListener         *stoppableTCPListener
    listenerStoppedError = fmt.Errorf("Listener has stopped")
)

type HttpConfig struct {
    ListenAddress string
    ListenPort    uint
    CorsDomain    string
}

func StartHttp(cfg HttpConfig, codec codec.Codec, apis ...api.EthereumApi) error {
    if httpListener != nil {
        if fmt.Sprintf("%s:%d", cfg.ListenAddress, cfg.ListenPort) != httpListener.Addr().String() {
            return fmt.Errorf("RPC service already running on %s ", httpListener.Addr().String())
        }
        return nil // RPC service already running on given host/port
    }

    l, err := newStoppableTCPListener(fmt.Sprintf("%s:%d", cfg.ListenAddress, cfg.ListenPort))
    if err != nil {
        glog.V(logger.Error).Infof("Can't listen on %s:%d: %v", cfg.ListenAddress, cfg.ListenPort, err)
        return err
    }
    httpListener = l

    api := api.Merge(apis...)
    var handler http.Handler
    if len(cfg.CorsDomain) > 0 {
        var opts cors.Options
        opts.AllowedMethods = []string{"POST"}
        opts.AllowedOrigins = strings.Split(cfg.CorsDomain, " ")

        c := cors.New(opts)
        handler = newStoppableHandler(c.Handler(gethHttpHandler(codec, api)), l.stop)
    } else {
        handler = newStoppableHandler(gethHttpHandler(codec, api), l.stop)
    }

    go http.Serve(l, handler)

    return nil
}

func StopHttp() {
    if httpListener != nil {
        httpListener.Stop()
        httpListener = nil
    }
}

type httpClient struct {
    codec codec.ApiCoder
}

// Create a new in process client
func NewHttpClient(cfg HttpConfig, codec codec.Codec) *httpClient {
    return &httpClient{
        codec: codec.New(nil),
    }
}

func (self *httpClient) Close() {
    // do nothing
}

func (self *httpClient) Send(req interface{}) error {
    return nil
}

func (self *httpClient) Recv() (interface{}, error) {
    return nil, nil
}