Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions cors-middleware/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# CORS Middleware Example

This example demonstrates how to enable **Cross-Origin Resource Sharing (CORS)** in a Gin web server.
It also provides basic RESTful endpoints (`GET`, `POST`, `PUT`, `DELETE`) to verify that cross-origin requests are properly handled.

---

## Features
- Custom CORS middleware allowing all origins (`*`)
- RESTful routes for `/ping` and `/data/:id`
- JSON responses with timestamps
- Handles `OPTIONS` preflight requests
- Includes logging for incoming requests

---

## Run

```bash
go run main.go
61 changes: 61 additions & 0 deletions cors-middleware/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package main

import (
"fmt"
"log"
"net/http"
"time"

"github.com/gin-gonic/gin"
)

func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
if c.Request.Method == "OPTIONS" {
c.Writer.Header().Set("Access-Control-Max-Age", "86400")
c.AbortWithStatus(http.StatusNoContent)
return
}
c.Next()
}
}

func main() {
r := gin.Default()
r.Use(CORSMiddleware())
r.GET("/ping", func(c *gin.Context) {
log.Println("Received a GET /ping request.")
c.JSON(http.StatusOK, gin.H{
"message": "pong",
"time": time.Now().Format(time.RFC3339),
})
})
r.POST("/data", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"status": "success",
"action": "Created",
"message": "Data processed successfully via POST.",
})
})
r.PUT("/data/:id", func(c *gin.Context) {
id := c.Param("id")
c.JSON(http.StatusOK, gin.H{
"status": "success",
"action": "Updated",
"message": fmt.Sprintf("Successfully processed PUT for resource ID: %s", id),
})
})
r.DELETE("/data/:id", func(c *gin.Context) {
id := c.Param("id")
c.JSON(http.StatusOK, gin.H{
"status": "success",
"action": "Deleted",
"message": fmt.Sprintf("Successfully processed DELETE for resource ID: %s", id),
})
})
log.Fatal(r.Run(":8080"))
}