Browse Source

loopd: add option to configure CORS origin

pull/148/head
Oliver Gugger 1 year ago
parent
commit
8c7eee2ba9
No known key found for this signature in database GPG Key ID: 8E4256593F177720
2 changed files with 15 additions and 1 deletions
  1. +1
    -0
      loopd/config.go
  2. +14
    -1
      loopd/daemon.go

+ 1
- 0
loopd/config.go View File

@ -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)"`

+ 14
- 1
loopd/daemon.go View File

@ -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)
})
}

Loading…
Cancel
Save