diff --git a/loopd/config.go b/loopd/config.go index 3fb05fb..9aa313b 100644 --- a/loopd/config.go +++ b/loopd/config.go @@ -35,6 +35,7 @@ type config struct { TLSPathSwapSrv string `long:"tlspathswapserver" description:"Path to swap server tls certificate. Only needed if the swap server uses a self-signed certificate."` RPCListen string `long:"rpclisten" description:"Address to listen on for gRPC clients"` RESTListen string `long:"restlisten" description:"Address to listen on for REST clients"` + CORSOrigin string `long:"corsorigin" description:"The value to send in the Access-Control-Allow-Origin header. Header will be omitted if empty."` LogDir string `long:"logdir" description:"Directory to log output."` MaxLogFiles int `long:"maxlogfiles" description:"Maximum logfiles to keep (0 for no rotation)"` diff --git a/loopd/daemon.go b/loopd/daemon.go index 358841e..f226331 100644 --- a/loopd/daemon.go +++ b/loopd/daemon.go @@ -119,6 +119,10 @@ func daemon(config *config, lisCfg *listenerCfg) error { ctx, cancel := context.WithCancel(context.Background()) defer cancel() mux := proxy.NewServeMux(customMarshalerOption) + var restHandler http.Handler = mux + if config.CORSOrigin != "" { + restHandler = allowCORS(restHandler, config.CORSOrigin) + } proxyOpts := []grpc.DialOption{ grpc.WithInsecure(), grpc.WithDefaultCallOptions(maxMsgRecvSize), @@ -141,7 +145,7 @@ func daemon(config *config, lisCfg *listenerCfg) error { log.Infof("Starting REST proxy listener") defer restListener.Close() - proxy := &http.Server{Handler: mux} + proxy := &http.Server{Handler: restHandler} go func() { err := proxy.Serve(restListener) @@ -225,3 +229,12 @@ func daemon(config *config, lisCfg *listenerCfg) error { return nil } + +// allowCORS wraps the given http.Handler with a function that adds the +// Access-Control-Allow-Origin header to the response. +func allowCORS(handler http.Handler, origin string) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", origin) + handler.ServeHTTP(w, r) + }) +}