Skip to content

Commit ba7a018

Browse files
authored
Merge pull request #148 from guggero/cors-header
loopd: add option to configure CORS origin
2 parents 7b4eb6e + ae376a4 commit ba7a018

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
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: 15 additions & 2 deletions
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)
@@ -214,7 +218,7 @@ func daemon(config *config, lisCfg *listenerCfg) error {
214218
// Debug code to dump goroutines on hanging exit.
215219
go func() {
216220
time.Sleep(5 * time.Second)
217-
pprof.Lookup("goroutine").WriteTo(os.Stdout, 1)
221+
_ = pprof.Lookup("goroutine").WriteTo(os.Stdout, 1)
218222
}()
219223

220224
cancel()
@@ -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)