Skip to content

Commit

Permalink
Add a setting to allow all access.
Browse files Browse the repository at this point in the history
  • Loading branch information
Scott Warren committed Feb 3, 2022
1 parent 7b02762 commit 48bc20c
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
10 changes: 9 additions & 1 deletion cmd/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand All @@ -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)

Expand All @@ -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,
Expand Down
6 changes: 4 additions & 2 deletions internal/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 48bc20c

Please sign in to comment.