-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
TakSeBiegam
committed
Dec 13, 2023
1 parent
984a8e7
commit 7046594
Showing
1 changed file
with
53 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |