Skip to content

Commit 8c7eee2

Browse files
committed
loopd: add option to configure CORS origin
1 parent 7b4eb6e commit 8c7eee2

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

loopd/config.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ type config struct {
3535
TLSPathSwapSrv string `long:"tlspathswapserver" description:"Path to swap server tls certificate. Only needed if the swap server uses a self-signed certificate."`
3636
RPCListen string `long:"rpclisten" description:"Address to listen on for gRPC clients"`
3737
RESTListen string `long:"restlisten" description:"Address to listen on for REST clients"`
38+
CORSOrigin string `long:"corsorigin" description:"The value to send in the Access-Control-Allow-Origin header. Header will be omitted if empty."`
3839

3940
LogDir string `long:"logdir" description:"Directory to log output."`
4041
MaxLogFiles int `long:"maxlogfiles" description:"Maximum logfiles to keep (0 for no rotation)"`

loopd/daemon.go

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,10 @@ func daemon(config *config, lisCfg *listenerCfg) error {
119119
ctx, cancel := context.WithCancel(context.Background())
120120
defer cancel()
121121
mux := proxy.NewServeMux(customMarshalerOption)
122+
var restHandler http.Handler = mux
123+
if config.CORSOrigin != "" {
124+
restHandler = allowCORS(restHandler, config.CORSOrigin)
125+
}
122126
proxyOpts := []grpc.DialOption{
123127
grpc.WithInsecure(),
124128
grpc.WithDefaultCallOptions(maxMsgRecvSize),
@@ -141,7 +145,7 @@ func daemon(config *config, lisCfg *listenerCfg) error {
141145
log.Infof("Starting REST proxy listener")
142146

143147
defer restListener.Close()
144-
proxy := &http.Server{Handler: mux}
148+
proxy := &http.Server{Handler: restHandler}
145149

146150
go func() {
147151
err := proxy.Serve(restListener)
@@ -225,3 +229,12 @@ func daemon(config *config, lisCfg *listenerCfg) error {
225229

226230
return nil
227231
}
232+
233+
// allowCORS wraps the given http.Handler with a function that adds the
234+
// Access-Control-Allow-Origin header to the response.
235+
func allowCORS(handler http.Handler, origin string) http.Handler {
236+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
237+
w.Header().Set("Access-Control-Allow-Origin", origin)
238+
handler.ServeHTTP(w, r)
239+
})
240+
}

0 commit comments

Comments
 (0)