gin
Gin is a high-performance HTTP web framework written in Go. It provides a Martini-like API but with significantly better performance—up to 40 times faster—thanks to httprouter. Gin is designed for building REST APIs, web applications, and microservices.
Top Related Projects
High performance, minimalist Go web framework
⚡️ Express inspired web framework written in Go
A high performance HTTP request router that scales well
Package gorilla/mux is a powerful HTTP router and URL matcher for building Go web servers with 🦍
lightweight, idiomatic and composable router for building Go HTTP services
Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http
Quick Overview
Gin is a high-performance HTTP web framework written in Go (Golang). It features a martini-like API with much better performance, up to 40 times faster. Gin is designed to be simple, fast, and flexible, making it ideal for building web applications and microservices.
Pros
- Extremely fast and efficient, with minimal memory footprint
- Easy to learn and use, with a simple and intuitive API
- Extensive middleware support for customization and extensibility
- Built-in support for JSON validation and rendering
Cons
- Less mature compared to some other Go web frameworks
- Limited built-in templating options
- Smaller community and ecosystem compared to more established frameworks
- May be overkill for very simple applications
Code Examples
- Basic HTTP server:
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080
}
- Handling URL parameters:
func main() {
router := gin.Default()
router.GET("/user/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
})
router.Run(":8080")
}
- Using middleware:
func main() {
r := gin.New()
r.Use(gin.Logger())
r.Use(gin.Recovery())
r.GET("/", func(c *gin.Context) {
c.String(200, "Hello World!")
})
r.Run(":8080")
}
Getting Started
To start using Gin, follow these steps:
- Install Gin:
go get -u github.com/gin-gonic/gin
- Create a new Go file (e.g.,
main.go) and add the following code:
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.String(200, "Hello, Gin!")
})
r.Run() // listen and serve on 0.0.0.0:8080
}
- Run your application:
go run main.go
- Open your browser and visit
http://localhost:8080to see your Gin application in action.
Competitor Comparisons
High performance, minimalist Go web framework
Pros of Echo
- More feature-rich with built-in middleware for JWT, CORS, and rate limiting
- Better documentation and more comprehensive examples
- Slightly faster performance in some benchmarks
Cons of Echo
- Larger codebase and slightly steeper learning curve
- Less community adoption and fewer third-party packages
- More opinionated structure, which may limit flexibility in some cases
Code Comparison
Echo:
e := echo.New()
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})
e.Logger.Fatal(e.Start(":1323"))
Gin:
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "Hello, World!")
})
r.Run(":8080")
Both Echo and Gin are popular Go web frameworks with similar syntax and functionality. Echo offers more built-in features and middleware, while Gin is known for its simplicity and performance. The choice between the two often comes down to personal preference and specific project requirements. Echo's more comprehensive feature set may be beneficial for larger projects, while Gin's simplicity and performance make it attractive for smaller applications or microservices.
⚡️ Express inspired web framework written in Go
Pros of Fiber
- Higher performance and lower memory usage
- Built-in WebSocket support
- More extensive middleware ecosystem
Cons of Fiber
- Less mature and stable compared to Gin
- Smaller community and fewer third-party integrations
- Steeper learning curve for developers familiar with net/http
Code Comparison
Gin example:
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{"message": "pong"})
})
r.Run()
Fiber example:
app := fiber.New()
app.Get("/ping", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{"message": "pong"})
})
app.Listen(":3000")
Both frameworks offer similar syntax for routing and handling requests. Fiber uses a more modern approach with error handling and a custom context type. Gin follows a pattern closer to the standard net/http library, which may be more familiar to Go developers.
While Fiber boasts higher performance, Gin's maturity and extensive community support make it a reliable choice for many projects. The decision between the two often depends on specific project requirements and developer preferences.
A high performance HTTP request router that scales well
Pros of httprouter
- Extremely lightweight and fast, with minimal overhead
- Simple and straightforward API, easy to learn and use
- Excellent performance for basic routing needs
Cons of httprouter
- Limited middleware support compared to Gin
- Fewer built-in features and utilities
- Less active community and ecosystem
Code Comparison
httprouter:
router := httprouter.New()
router.GET("/", Index)
router.GET("/hello/:name", Hello)
log.Fatal(http.ListenAndServe(":8080", router))
Gin:
router := gin.Default()
router.GET("/", Index)
router.GET("/hello/:name", Hello)
router.Run(":8080")
Summary
httprouter is a minimalist, high-performance HTTP router for Go, focusing on speed and simplicity. It's ideal for projects that require basic routing without additional features. Gin, built on top of httprouter, offers a more comprehensive framework with middleware support, input validation, and a larger ecosystem. While httprouter excels in raw performance, Gin provides a richer set of tools and abstractions for building web applications. The choice between the two depends on the specific needs of your project, balancing between simplicity and feature set.
Package gorilla/mux is a powerful HTTP router and URL matcher for building Go web servers with 🦍
Pros of Mux
- More flexible routing with support for complex URL patterns and variables
- Better integration with standard Go HTTP library
- Lightweight and minimalistic, allowing for more control over the application structure
Cons of Mux
- Less built-in functionality compared to Gin
- Slower performance in high-load scenarios
- Requires more manual setup for common web application features
Code Comparison
Mux:
r := mux.NewRouter()
r.HandleFunc("/users/{id:[0-9]+}", GetUser).Methods("GET")
http.ListenAndServe(":8080", r)
Gin:
r := gin.Default()
r.GET("/users/:id", GetUser)
r.Run(":8080")
Both Gin and Mux are popular Go web frameworks, but they have different focuses. Gin is designed for high performance and comes with more built-in features, making it easier to quickly develop web applications. Mux, on the other hand, offers more flexibility in routing and integrates seamlessly with the standard Go HTTP library, giving developers more control over their application structure.
Gin provides better performance out of the box, especially in high-load scenarios, and includes features like middleware support and JSON validation. Mux is more lightweight and allows for more complex routing patterns, which can be beneficial for applications with intricate URL structures.
The choice between Gin and Mux often depends on the specific requirements of the project, such as performance needs, routing complexity, and desired level of control over the application structure.
lightweight, idiomatic and composable router for building Go HTTP services
Pros of Chi
- Lightweight and minimalist design, offering more flexibility
- Follows standard Go HTTP conventions, making it easier for Go developers
- Built-in support for middleware chaining and context-based request handling
Cons of Chi
- Less feature-rich out of the box compared to Gin
- Smaller community and ecosystem
- Requires more manual setup for certain functionalities
Code Comparison
Chi:
r := chi.NewRouter()
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Welcome"))
})
Gin:
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "Welcome")
})
Both Chi and Gin are popular Go web frameworks, but they have different philosophies. Chi focuses on simplicity and adhering to Go's standard library patterns, while Gin offers more built-in features and performance optimizations. Chi's approach may appeal to developers who prefer a minimalist framework that closely follows Go idioms, whereas Gin might be more suitable for those seeking a feature-rich solution with extensive middleware support out of the box.
Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http
Pros of fasthttp
- Significantly higher performance and lower memory usage
- Optimized for high-concurrency scenarios
- Provides low-level control over HTTP operations
Cons of fasthttp
- Steeper learning curve due to its low-level nature
- Less extensive middleware ecosystem compared to Gin
- Not fully compatible with net/http, requiring some code adjustments
Code Comparison
fasthttp example:
func handleFastHTTP(ctx *fasthttp.RequestCtx) {
fmt.Fprintf(ctx, "Hello, %s!", ctx.UserValue("name"))
}
fasthttp.ListenAndServe(":8080", handleFastHTTP)
Gin example:
r := gin.Default()
r.GET("/hello/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello, %s!", name)
})
r.Run(":8080")
fasthttp focuses on raw performance and low-level control, while Gin provides a more user-friendly API with built-in features like routing and middleware support. fasthttp excels in high-concurrency scenarios but requires more manual configuration. Gin offers a gentler learning curve and better compatibility with the standard library, making it suitable for a wider range of applications.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Gin Web Framework
ð° Announcing Gin 1.11.0!
Read about the latest features and improvements in Gin 1.11.0 on our official blog.
Gin is a high-performance HTTP web framework written in Go. It provides a Martini-like API but with significantly better performanceâup to 40 times fasterâthanks to httprouter. Gin is designed for building REST APIs, web applications, and microservices where speed and developer productivity are essential.
Why choose Gin?
Gin combines the simplicity of Express.js-style routing with Go's performance characteristics, making it ideal for:
- Building high-throughput REST APIs
- Developing microservices that need to handle many concurrent requests
- Creating web applications that require fast response times
- Prototyping web services quickly with minimal boilerplate
Gin's key features:
- Zero allocation router - Extremely memory-efficient routing with no heap allocations
- High performance - Benchmarks show superior speed compared to other Go web frameworks
- Middleware support - Extensible middleware system for authentication, logging, CORS, etc.
- Crash-free - Built-in recovery middleware prevents panics from crashing your server
- JSON validation - Automatic request/response JSON binding and validation
- Route grouping - Organize related routes and apply common middleware
- Error management - Centralized error handling and logging
- Built-in rendering - Support for JSON, XML, HTML templates, and more
- Extensible - Large ecosystem of community middleware and plugins
Getting Started
Prerequisites
- Go version: Gin requires Go version 1.24 or above
- Basic Go knowledge: Familiarity with Go syntax and package management is helpful
Installation
With Go's module support, simply import Gin in your code and Go will automatically fetch it during build:
import "github.com/gin-gonic/gin"
Your First Gin Application
Here's a complete example that demonstrates Gin's simplicity:
package main
import (
"log"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
// Create a Gin router with default middleware (logger and recovery)
r := gin.Default()
// Define a simple GET endpoint
r.GET("/ping", func(c *gin.Context) {
// Return JSON response
c.JSON(http.StatusOK, gin.H{
"message": "pong",
})
})
// Start server on port 8080 (default)
// Server will listen on 0.0.0.0:8080 (localhost:8080 on Windows)
if err := r.Run(); err != nil {
log.Fatalf("failed to run server: %v", err)
}
}
Running the application:
-
Save the code above as
main.go -
Run the application:
go run main.go -
Open your browser and visit
http://localhost:8080/ping -
You should see:
{"message":"pong"}
What this example demonstrates:
- Creating a Gin router with default middleware
- Defining HTTP endpoints with simple handler functions
- Returning JSON responses
- Starting an HTTP server
Next Steps
After running your first Gin application, explore these resources to learn more:
ð Learning Resources
- Gin Quick Start Guide - Comprehensive tutorial with API examples and build configurations
- Example Repository - Ready-to-run examples demonstrating various Gin use cases:
- REST API development
- Authentication & middleware
- File uploads and downloads
- WebSocket connections
- Template rendering
ð Documentation
API Reference
- Go.dev API Documentation - Complete API reference with examples
User Guides
The comprehensive documentation is available on gin-gonic.com in multiple languages:
- English | ç®ä½ä¸æ | ç¹é«ä¸æ
- æ¥æ¬èª | íêµì´ | Español
- Turkish | Persian | Português
- Russian | Indonesian
Official Tutorials
â¡ Performance Benchmarks
Gin demonstrates exceptional performance compared to other Go web frameworks. It uses a custom version of HttpRouter for maximum efficiency. View detailed benchmarks â
Gin vs. Other Go Frameworks (GitHub API routing benchmark):
| Benchmark name | (1) | (2) | (3) | (4) |
|---|---|---|---|---|
| BenchmarkGin_GithubAll | 43550 | 27364 ns/op | 0 B/op | 0 allocs/op |
| BenchmarkAce_GithubAll | 40543 | 29670 ns/op | 0 B/op | 0 allocs/op |
| BenchmarkAero_GithubAll | 57632 | 20648 ns/op | 0 B/op | 0 allocs/op |
| BenchmarkBear_GithubAll | 9234 | 216179 ns/op | 86448 B/op | 943 allocs/op |
| BenchmarkBeego_GithubAll | 7407 | 243496 ns/op | 71456 B/op | 609 allocs/op |
| BenchmarkBone_GithubAll | 420 | 2922835 ns/op | 720160 B/op | 8620 allocs/op |
| BenchmarkChi_GithubAll | 7620 | 238331 ns/op | 87696 B/op | 609 allocs/op |
| BenchmarkDenco_GithubAll | 18355 | 64494 ns/op | 20224 B/op | 167 allocs/op |
| BenchmarkEcho_GithubAll | 31251 | 38479 ns/op | 0 B/op | 0 allocs/op |
| BenchmarkGocraftWeb_GithubAll | 4117 | 300062 ns/op | 131656 B/op | 1686 allocs/op |
| BenchmarkGoji_GithubAll | 3274 | 416158 ns/op | 56112 B/op | 334 allocs/op |
| BenchmarkGojiv2_GithubAll | 1402 | 870518 ns/op | 352720 B/op | 4321 allocs/op |
| BenchmarkGoJsonRest_GithubAll | 2976 | 401507 ns/op | 134371 B/op | 2737 allocs/op |
| BenchmarkGoRestful_GithubAll | 410 | 2913158 ns/op | 910144 B/op | 2938 allocs/op |
| BenchmarkGorillaMux_GithubAll | 346 | 3384987 ns/op | 251650 B/op | 1994 allocs/op |
| BenchmarkGowwwRouter_GithubAll | 10000 | 143025 ns/op | 72144 B/op | 501 allocs/op |
| BenchmarkHttpRouter_GithubAll | 55938 | 21360 ns/op | 0 B/op | 0 allocs/op |
| BenchmarkHttpTreeMux_GithubAll | 10000 | 153944 ns/op | 65856 B/op | 671 allocs/op |
| BenchmarkKocha_GithubAll | 10000 | 106315 ns/op | 23304 B/op | 843 allocs/op |
| BenchmarkLARS_GithubAll | 47779 | 25084 ns/op | 0 B/op | 0 allocs/op |
| BenchmarkMacaron_GithubAll | 3266 | 371907 ns/op | 149409 B/op | 1624 allocs/op |
| BenchmarkMartini_GithubAll | 331 | 3444706 ns/op | 226551 B/op | 2325 allocs/op |
| BenchmarkPat_GithubAll | 273 | 4381818 ns/op | 1483152 B/op | 26963 allocs/op |
| BenchmarkPossum_GithubAll | 10000 | 164367 ns/op | 84448 B/op | 609 allocs/op |
| BenchmarkR2router_GithubAll | 10000 | 160220 ns/op | 77328 B/op | 979 allocs/op |
| BenchmarkRivet_GithubAll | 14625 | 82453 ns/op | 16272 B/op | 167 allocs/op |
| BenchmarkTango_GithubAll | 6255 | 279611 ns/op | 63826 B/op | 1618 allocs/op |
| BenchmarkTigerTonic_GithubAll | 2008 | 687874 ns/op | 193856 B/op | 4474 allocs/op |
| BenchmarkTraffic_GithubAll | 355 | 3478508 ns/op | 820744 B/op | 14114 allocs/op |
| BenchmarkVulcan_GithubAll | 6885 | 193333 ns/op | 19894 B/op | 609 allocs/op |
- (1): Total Repetitions achieved in constant time, higher means more confident result
- (2): Single Repetition Duration (ns/op), lower is better
- (3): Heap Memory (B/op), lower is better
- (4): Average Allocations per Repetition (allocs/op), lower is better
ð Middleware Ecosystem
Gin has a rich ecosystem of middleware for common web development needs. Explore community-contributed middleware:
- gin-contrib - Official middleware collection including:
- Authentication (JWT, Basic Auth, Sessions)
- CORS, Rate limiting, Compression
- Logging, Metrics, Tracing
- Static file serving, Template engines
- gin-gonic/contrib - Additional community middleware
ð¢ Production Usage
Gin powers many high-traffic applications and services in production:
- gorush - High-performance push notification server
- fnproject - Container-native, serverless platform
- photoprism - AI-powered personal photo management
- lura - Ultra-performant API Gateway framework
- picfit - Real-time image processing server
- dkron - Distributed job scheduling system
ð¤ Contributing
Gin is the work of hundreds of contributors from around the world. We welcome and appreciate your contributions!
How to Contribute
- ð Report bugs - Help us identify and fix issues
- ð¡ Suggest features - Share your ideas for improvements
- ð Improve documentation - Help make our docs clearer
- ð§ Submit code - Fix bugs or implement new features
- 𧪠Write tests - Improve our test coverage
Getting Started with Contributing
- Check out our CONTRIBUTING.md for detailed guidelines
- Join our community discussions and ask questions
All contributions are valued and help make Gin better for everyone!
Top Related Projects
High performance, minimalist Go web framework
⚡️ Express inspired web framework written in Go
A high performance HTTP request router that scales well
Package gorilla/mux is a powerful HTTP router and URL matcher for building Go web servers with 🦍
lightweight, idiomatic and composable router for building Go HTTP services
Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot