Fix CORS Error in Go — Gin, Echo, Fiber, net/http
Updated April 2026
Reading this article? Verify your fix in real-time. Test your Go API CORS config live → CORSFixer
Go web frameworks do not add CORS headers by default. Each framework has a built-in or external CORS middleware. Here is the exact setup for the four most common stacks.
Browser Console
Access to fetch at 'http://localhost:8080/api/data' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.Gin — gin-contrib/cors
go get github.com/gin-contrib/cors
package main
import ( "github.com/gin-gonic/gin" "github.com/gin-contrib/cors"
)
func main() { r := gin.Default() r.Use(cors.New(cors.Config{ AllowOrigins: []string{"https://yourapp.com"}, AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, AllowHeaders: []string{"Origin", "Content-Type", "Authorization"}, AllowCredentials: false, MaxAge: 86400, })) r.GET("/api/data", func(c *gin.Context) { c.JSON(200, gin.H{"status": "ok"}) }) r.Run(":8080")
}
Echo — built-in CORS middleware
package main
import ( "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware"
)
func main() { e := echo.New() e.Use(middleware.CORSWithConfig(middleware.CORSConfig{ AllowOrigins: []string{"https://yourapp.com"}, AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, AllowHeaders: []string{"Authorization", "Content-Type"}, AllowCredentials: false, })) e.GET("/api/data", func(c echo.Context) error { return c.JSON(200, map[string]string{"status": "ok"}) }) e.Start(":8080")
}
Fiber — built-in CORS middleware
package main
import ( "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/cors"
)
func main() { app := fiber.New() app.Use(cors.New(cors.Config{ AllowOrigins: "https://yourapp.com", AllowMethods: "GET,POST,PUT,DELETE,OPTIONS", AllowHeaders: "Origin,Content-Type,Authorization", AllowCredentials: false, })) app.Get("/api/data", func(c *fiber.Ctx) error { return c.JSON(fiber.Map{"status": "ok"}) }) app.Listen(":8080")
}
Standard net/http — no framework
package main
import "net/http"
func corsMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "https://yourapp.com") w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization") if r.Method == http.MethodOptions { w.WriteHeader(http.StatusNoContent) return } next.ServeHTTP(w, r) })
}
func main() { mux := http.NewServeMux() mux.HandleFunc("/api/data", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`{"status":"ok"}`)) }) http.ListenAndServe(":8080", corsMiddleware(mux))
} Test your Go API CORS config live → CORSFixer