diff options
author | Bas van Kervel <bas@ethdev.com> | 2015-06-16 19:07:13 +0800 |
---|---|---|
committer | Bas van Kervel <bas@ethdev.com> | 2015-06-22 14:54:21 +0800 |
commit | fd764d4ff7bd7e75dfdd7f733f50dd3805d4b3f2 (patch) | |
tree | 58af87ef1e8c78cfb05a6b756ad5e0b283590a0f /rpc/comms/http.go | |
parent | 60c2ccd99cd9acdb628a9ba5e16ad0e7e52b7e17 (diff) | |
download | dexon-fd764d4ff7bd7e75dfdd7f733f50dd3805d4b3f2.tar dexon-fd764d4ff7bd7e75dfdd7f733f50dd3805d4b3f2.tar.gz dexon-fd764d4ff7bd7e75dfdd7f733f50dd3805d4b3f2.tar.bz2 dexon-fd764d4ff7bd7e75dfdd7f733f50dd3805d4b3f2.tar.lz dexon-fd764d4ff7bd7e75dfdd7f733f50dd3805d4b3f2.tar.xz dexon-fd764d4ff7bd7e75dfdd7f733f50dd3805d4b3f2.tar.zst dexon-fd764d4ff7bd7e75dfdd7f733f50dd3805d4b3f2.zip |
added comms http
Diffstat (limited to 'rpc/comms/http.go')
-rw-r--r-- | rpc/comms/http.go | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/rpc/comms/http.go b/rpc/comms/http.go new file mode 100644 index 000000000..1fea8dc1d --- /dev/null +++ b/rpc/comms/http.go @@ -0,0 +1,65 @@ +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 + } +} |