changeset 325:c23eb0f34e39

Added CORS support.
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Thu, 02 Aug 2018 18:07:35 +0200
parents 8bacd556ea39
children a7b2db8b3d18
files 3rdpartylibs.sh cmd/gemma/root.go config/config.go
diffstat 3 files changed, 23 insertions(+), 2 deletions(-) [+]
line wrap: on
line diff
--- a/3rdpartylibs.sh	Thu Aug 02 17:28:07 2018 +0200
+++ b/3rdpartylibs.sh	Thu Aug 02 18:07:35 2018 +0200
@@ -6,3 +6,4 @@
 go get -u -v github.com/spf13/viper
 go get -u -v github.com/gorilla/mux
 go get -u -v gopkg.in/gomail.v2
+go get -u -v github.com/rs/cors
--- a/cmd/gemma/root.go	Thu Aug 02 17:28:07 2018 +0200
+++ b/cmd/gemma/root.go	Thu Aug 02 18:07:35 2018 +0200
@@ -15,6 +15,7 @@
 	"gemma.intevation.de/gemma/controllers"
 
 	"github.com/gorilla/mux"
+	"github.com/rs/cors"
 	"github.com/spf13/cobra"
 	"github.com/spf13/pflag"
 	"github.com/spf13/viper"
@@ -59,6 +60,8 @@
 	fl().StringVar(&cfg.MailFrom, "mail-from", "noreplay@localhost", "from line of mails")
 	fl().StringVar(&cfg.MailHelo, "mail-helo", "localhost", "name of server to send mail from.")
 
+	fl().StringSliceVar(&cfg.AllowedOrigins, "allowed-origins", []string{"foo.org"}, "allow access for remote origins")
+
 	vbind := func(name string) { viper.BindPFlag(name, fl().Lookup(name)) }
 
 	vbind("dbhost")
@@ -81,6 +84,8 @@
 	vbind("mail-password")
 	vbind("mail-from")
 	vbind("mail-helo")
+
+	vbind("allowed-origins")
 }
 
 func initConfig() {
@@ -121,7 +126,8 @@
 	cmd.Flags().VisitAll(func(f *pflag.Flag) {
 		if !f.Changed {
 			if viper.IsSet(f.Name) {
-				cmd.Flags().Set(f.Name, viper.GetString(f.Name))
+				s := fmt.Sprintf("%s", viper.Get(f.Name))
+				cmd.Flags().Set(f.Name, s)
 			}
 		}
 	})
@@ -148,7 +154,19 @@
 	addr := fmt.Sprintf("%s:%d", config.Config.WebHost, config.Config.WebPort)
 	log.Printf("listen on %s\n", addr)
 
-	server := http.Server{Addr: addr, Handler: m}
+	var h http.Handler
+
+	if len(config.Config.AllowedOrigins) > 0 {
+		c := cors.New(cors.Options{
+			AllowedOrigins: config.Config.AllowedOrigins,
+			Debug:          true,
+		})
+		h = c.Handler(m)
+	} else {
+		h = m
+	}
+
+	server := http.Server{Addr: addr, Handler: h}
 
 	done := make(chan error)
 
--- a/config/config.go	Thu Aug 02 17:28:07 2018 +0200
+++ b/config/config.go	Thu Aug 02 18:07:35 2018 +0200
@@ -23,4 +23,6 @@
 	MailPassword string
 	MailFrom     string
 	MailHelo     string
+
+	AllowedOrigins []string
 }