CORS Middleware Configuration and Usage
This document explains how to configure and use the CORS (Cross-Origin Resource Sharing) middleware in the Go REST API Boilerplate project. The middleware is implemented using the gin-contrib/cors
package and is designed to be flexible and configurable.
Overview
The CORS middleware allows you to control which origins can access your API. It's crucial for securing your API while still allowing legitimate cross-origin requests.
Configuration
The middleware is configured in the CORSMiddleware()
function, which returns a gin.HandlerFunc
. Here's how it works:
-
Default Configuration: It starts with the default CORS configuration.
-
Allowed Origins:
- The middleware checks for an environment variable
ALLOWED_ORIGINS
. - If set, it uses these origins as the allowed origins.
- If not set, it allows any origin that starts with
http://localhost
orhttps://localhost
.
- The middleware checks for an environment variable
-
Allowed Methods: The middleware allows the following HTTP methods:
- GET
- POST
- PUT
- PATCH
- DELETE
- OPTIONS
-
Allowed Headers: The middleware allows the following headers:
- Origin
- Content-Type
- Accept
- Authorization
Usage
To use this middleware in your Gin application, follow these steps:
- Import the middleware package:
import "github.com/nicobistolfi/go-rest-api/internal/api/middleware"
- Add the middleware to your Gin router:
func main() {
router := gin.Default()
// Apply the CORS middleware
router.Use(middleware.CORSMiddleware())
// Your routes go here
// ...
router.Run()
}
Configuration via Environment Variables
To configure allowed origins using environment variables:
-
Set the
ALLOWED_ORIGINS
environment variable before running your application. Multiple origins should be comma-separated.Example:
export ALLOWED_ORIGINS="https://example.com,https://api.example.com"
-
If
ALLOWED_ORIGINS
is not set, the middleware will default to allowing any origin that starts withhttp://localhost
orhttps://localhost
.
Customization
If you need to customize the CORS settings further:
- Modify the
CORSMiddleware()
function in the middleware package. - You can adjust allowed methods, headers, or add more sophisticated origin checking logic.
Example of adding a custom header:
config.AllowHeaders = append(config.AllowHeaders, "X-Custom-Header")
Security Considerations
- Restrict Origins: In production, always set
ALLOWED_ORIGINS
to a specific list of trusted domains. - Least Privilege: Only expose the methods and headers that your API actually needs.
- Credentials: If your API requires credentials (cookies, HTTP authentication), you may need to set
config.AllowCredentials = true
. Use this with caution and ensureAllowOrigins
is not set to*
.
Troubleshooting
If you're experiencing CORS issues:
- Check that the
ALLOWED_ORIGINS
environment variable is set correctly. - Ensure that the origin making the request matches exactly with one of the allowed origins (including the protocol,
http://
orhttps://
). - Verify that the request is using an allowed method and only includes allowed headers.
Example
Here's a complete example of setting up a Gin router with the CORS middleware:
package main
import (
"github.com/gin-gonic/gin"
"github.com/nicobistolfi/go-rest-api/internal/api/middleware"
)
func main() {
// Set up Gin
router := gin.Default()
// Apply CORS middleware
router.Use(middleware.CORSMiddleware())
// Define a route
router.GET("/api/data", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "This is CORS-enabled data",
})
})
// Run the server
router.Run(":8080")
}
In this example, the CORS middleware will be applied to all routes. The allowed origins will be determined by the ALLOWED_ORIGINS
environment variable, or default to localhost if not set.
By following these guidelines, you can effectively implement and customize CORS in your Go REST API, ensuring that your API is accessible to the intended clients while maintaining security.