diff --git a/README.md b/README.md index 3df6300..fd0e60a 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,13 @@ When doing requests, it's good to know that: `go run main.go start -l` + - Disable CORS. To allow access from any host (not secure) `-a` or `--allorigins`. Default value is `false`. + +This adds the header "Access-Control-Allow-Origin: *" which tells the browser to allow from any origin. + +`go run main.go start -a` + + ## Known issues - For users running **macOS Catalina** and newer versions, apple will prevent binary from run as it hasn't been notarized and signed. To overcome this issue, you can [add a security exception](https://support.apple.com/en-us/HT202491) diff --git a/cmd/start.go b/cmd/start.go index a3c866f..6803577 100644 --- a/cmd/start.go +++ b/cmd/start.go @@ -50,6 +50,9 @@ Please note that only array data type resources are supported`, // Optional flag to enable logs. startCmd.Flags().BoolP("logs", "l", false, "Enable logs") + // Optional flag to allow all origins + startCmd.Flags().BoolP("allorigins", "a", false, "Allow any Origin ie 'Access-Control-Allow-Origin: *' in the header") + return startCmd } @@ -72,6 +75,11 @@ func runStart(cmd *cobra.Command, _ []string) error { return fmt.Errorf("%w: logs", errFailedParseFlag) } + allorigins, err := cmd.Flags().GetBool("allorigins") + if err != nil { + return fmt.Errorf("%w: logs", errFailedParseFlag) + } + // Setup logger. logger.Setup(logs) @@ -90,7 +98,7 @@ func runStart(cmd *cobra.Command, _ []string) error { // Setup API server. api := &http.Server{ Addr: ":" + port, - Handler: handler.Setup(resourceStorage), + Handler: handler.Setup(resourceStorage, allorigins), // Good practice to set timeouts to avoid Slowloris attacks. WriteTimeout: time.Second * 15, ReadTimeout: time.Second * 15, diff --git a/internal/handler/handler.go b/internal/handler/handler.go index f94241f..1fbcb6a 100644 --- a/internal/handler/handler.go +++ b/internal/handler/handler.go @@ -14,11 +14,13 @@ import ( ) // Setup API handler based on provided resources. -func Setup(resourceStorage map[string]storage.Storage) http.Handler { +func Setup(resourceStorage map[string]storage.Storage, allow_all bool) http.Handler { router := mux.NewRouter().StrictSlash(true) router.Use(middleware.Recovery) router.Use(middleware.Logger) - router.Use(middleware.CorsAllowAll) + if allow_all { + router.Use(middleware.CorsAllowAll) + } // For each resource create the appropriate endpoint handlers. for resourceKey, storageSvc := range resourceStorage {