Skip to content

Commit

Permalink
feat: added cors package
Browse files Browse the repository at this point in the history
  • Loading branch information
TakSeBiegam committed Dec 13, 2023
1 parent 984a8e7 commit 7046594
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions pkg/cors/cors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package cors

import (
"net/http"
"os"
"strconv"
"strings"
)

type CorsOptions struct {
AllowedMethods, AllowedHeaders, AllowedOrigins []string
AllowedCredentials bool
}

func retriveOriginEnv(name string) []string {
return strings.Split(os.Getenv(name), " ")
}

func NewCors() CorsOptions {
allowedOrigins := []string{"*"}
if envOrigin := retriveOriginEnv("ALLOWED_ORIGINS"); envOrigin[0] != "" {
allowedOrigins = envOrigin
}
allowedMethods := []string{http.MethodHead,
http.MethodGet,
http.MethodPost,
http.MethodPut,
http.MethodPatch,
http.MethodDelete,
}
if envMethod := retriveOriginEnv("ALLOWED_METHODS"); envMethod[0] == "" {
allowedMethods = []string{"POST", "GET", "OPTIONS"}
}
allowedHeaders := []string{"*"}
if envHeaders := retriveOriginEnv("ALLOWED_HEADERS"); envHeaders[0] == "" {
allowedHeaders = []string{"Accept", "Authorization", "Origin", "Content-Type"}
}
allowedCredentials := true
var err error
if envCredentials := os.Getenv("ALLOWED_CREDENTIALS"); envCredentials != "" {
allowedCredentials, err = strconv.ParseBool(envCredentials)
if err != nil {
panic("cannot parse ALLOWED_CREDENTIALS env to boolean")
}
}
c := CorsOptions{
AllowedMethods: allowedMethods,
AllowedHeaders: allowedHeaders,
AllowedOrigins: allowedOrigins,
AllowedCredentials: allowedCredentials,
}
return c
}

0 comments on commit 7046594

Please sign in to comment.