feat: cors origins env var

This commit is contained in:
Florian Sylvain
2023-08-11 21:12:31 +02:00
parent d953a66f22
commit 318fd0f53a
2 changed files with 9 additions and 8 deletions
+3 -2
View File
@@ -19,9 +19,10 @@ TODO
### Environment variables ### Environment variables
| Name | Type | Description | Comment | | Name | Type | Description | Comment |
|-------------|--------|---------------------------------------|-----------------------------------------| |----------------------|--------|---------------------------------------|-----------------------------------------|
| PORT | int | The port the API will use | required |
| ENVIRONMENT | string | The environment the API is running in | required, `development` or `production` | | ENVIRONMENT | string | The environment the API is running in | required, `development` or `production` |
| PORT | int | The port the API will use | required |
| CORS_ALLOWED_ORIGINS | string | The allowed origins for CORS | required, semicolon separated list |
## API Usage ## API Usage
+4 -4
View File
@@ -12,9 +12,10 @@ import (
"log" "log"
"net/http" "net/http"
"os" "os"
"strings"
) )
var envVarsToLoad = []string{"PORT", "ENVIRONMENT"} var envVarsToLoad = []string{"PORT", "ENVIRONMENT", "CORS_ALLOWED_ORIGINS"}
func jsonContentTypeMiddleware(next http.Handler) http.Handler { func jsonContentTypeMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -70,9 +71,8 @@ func initRoutes() *chi.Mux {
frontend := initFrontendRoutes() frontend := initFrontendRoutes()
apiRouter := chi.NewRouter() apiRouter := chi.NewRouter()
// TODO use env variable for allowed origins
apiRouter.Use(cors.Handler(cors.Options{ apiRouter.Use(cors.Handler(cors.Options{
AllowedOrigins: []string{"https://*", "http://*"}, AllowedOrigins: strings.Split(os.Getenv("CORS_ALLOWED_ORIGINS"), ";"),
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"}, AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ExposedHeaders: []string{"Link"}, ExposedHeaders: []string{"Link"},
@@ -104,7 +104,7 @@ func main() {
initJwt() initJwt()
router := initRoutes() router := initRoutes()
fmt.Println("Server starting on port " + os.Getenv("PORT")) fmt.Println("Server starting on http://localhost:" + os.Getenv("PORT"))
err := http.ListenAndServe(":"+os.Getenv("PORT"), router) err := http.ListenAndServe(":"+os.Getenv("PORT"), router)
if err != nil { if err != nil {
panic(err) panic(err)