diff options
author | Maran <maran.hidskes@gmail.com> | 2017-01-05 18:57:41 +0800 |
---|---|---|
committer | Felix Lange <fjl@users.noreply.github.com> | 2017-01-05 18:57:41 +0800 |
commit | f087633efdf42f23ada99a5750af30320a7905a8 (patch) | |
tree | b905d58611b342650657c20810aa9cc1d44b73e2 /swarm/api | |
parent | bbce726c8a85e72141d9d7e690711738c09ede3b (diff) | |
download | dexon-f087633efdf42f23ada99a5750af30320a7905a8.tar dexon-f087633efdf42f23ada99a5750af30320a7905a8.tar.gz dexon-f087633efdf42f23ada99a5750af30320a7905a8.tar.bz2 dexon-f087633efdf42f23ada99a5750af30320a7905a8.tar.lz dexon-f087633efdf42f23ada99a5750af30320a7905a8.tar.xz dexon-f087633efdf42f23ada99a5750af30320a7905a8.tar.zst dexon-f087633efdf42f23ada99a5750af30320a7905a8.zip |
swarm/api/http: add support for CORS headers (#3388)
Diffstat (limited to 'swarm/api')
-rw-r--r-- | swarm/api/http/server.go | 26 |
1 files changed, 23 insertions, 3 deletions
diff --git a/swarm/api/http/server.go b/swarm/api/http/server.go index f82775f25..c8e79ab4e 100644 --- a/swarm/api/http/server.go +++ b/swarm/api/http/server.go @@ -24,6 +24,7 @@ import ( "io" "net/http" "regexp" + "strings" "sync" "time" @@ -31,6 +32,7 @@ import ( "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger/glog" "github.com/ethereum/go-ethereum/swarm/api" + "github.com/rs/cors" ) const ( @@ -53,19 +55,37 @@ type sequentialReader struct { lock sync.Mutex } +// Server is the basic configuration needs for the HTTP server and also +// includes CORS settings. +type Server struct { + Addr string + CorsString string +} + // browser API for registering bzz url scheme handlers: // https://developer.mozilla.org/en/docs/Web-based_protocol_handlers // electron (chromium) api for registering bzz url scheme handlers: // https://github.com/atom/electron/blob/master/docs/api/protocol.md // starts up http server -func StartHttpServer(api *api.Api, port string) { +func StartHttpServer(api *api.Api, server *Server) { serveMux := http.NewServeMux() serveMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { handler(w, r, api) }) - go http.ListenAndServe(":"+port, serveMux) - glog.V(logger.Info).Infof("Swarm HTTP proxy started on localhost:%s", port) + var allowedOrigins []string + for _, domain := range strings.Split(server.CorsString, ",") { + allowedOrigins = append(allowedOrigins, strings.TrimSpace(domain)) + } + c := cors.New(cors.Options{ + AllowedOrigins: allowedOrigins, + AllowedMethods: []string{"POST", "GET", "DELETE", "PATCH", "PUT"}, + MaxAge: 600, + }) + hdlr := c.Handler(serveMux) + + go http.ListenAndServe(server.Addr, hdlr) + glog.V(logger.Info).Infof("Swarm HTTP proxy started on localhost:%s", server.Addr) } func handler(w http.ResponseWriter, r *http.Request, a *api.Api) { |