Convert Figma logo to code with AI

gin-gonic logogin

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.

87,670
8,540
87,670
889

Top Related Projects

31,995

High performance, minimalist Go web framework

38,885

⚡️ Express inspired web framework written in Go

A high performance HTTP request router that scales well

21,764

Package gorilla/mux is a powerful HTTP router and URL matcher for building Go web servers with 🦍

21,330

lightweight, idiomatic and composable router for building Go HTTP services

23,059

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

  1. 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
}
  1. 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")
}
  1. 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:

  1. Install Gin:
go get -u github.com/gin-gonic/gin
  1. 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
}
  1. Run your application:
go run main.go
  1. Open your browser and visit http://localhost:8080 to see your Gin application in action.

Competitor Comparisons

31,995

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.

38,885

⚡️ 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.

21,764

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.

21,330

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.

23,059

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 Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Gin Web Framework

Build Status Trivy Security Scan codecov Go Report Card Go Reference Sourcegraph Open Source Helpers Release

📰 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:

  1. Save the code above as main.go

  2. Run the application:

    go run main.go
    
  3. Open your browser and visit http://localhost:8080/ping

  4. 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

User Guides

The comprehensive documentation is available on gin-gonic.com in multiple languages:

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_GithubAll4355027364 ns/op0 B/op0 allocs/op
BenchmarkAce_GithubAll4054329670 ns/op0 B/op0 allocs/op
BenchmarkAero_GithubAll5763220648 ns/op0 B/op0 allocs/op
BenchmarkBear_GithubAll9234216179 ns/op86448 B/op943 allocs/op
BenchmarkBeego_GithubAll7407243496 ns/op71456 B/op609 allocs/op
BenchmarkBone_GithubAll4202922835 ns/op720160 B/op8620 allocs/op
BenchmarkChi_GithubAll7620238331 ns/op87696 B/op609 allocs/op
BenchmarkDenco_GithubAll1835564494 ns/op20224 B/op167 allocs/op
BenchmarkEcho_GithubAll3125138479 ns/op0 B/op0 allocs/op
BenchmarkGocraftWeb_GithubAll4117300062 ns/op131656 B/op1686 allocs/op
BenchmarkGoji_GithubAll3274416158 ns/op56112 B/op334 allocs/op
BenchmarkGojiv2_GithubAll1402870518 ns/op352720 B/op4321 allocs/op
BenchmarkGoJsonRest_GithubAll2976401507 ns/op134371 B/op2737 allocs/op
BenchmarkGoRestful_GithubAll4102913158 ns/op910144 B/op2938 allocs/op
BenchmarkGorillaMux_GithubAll3463384987 ns/op251650 B/op1994 allocs/op
BenchmarkGowwwRouter_GithubAll10000143025 ns/op72144 B/op501 allocs/op
BenchmarkHttpRouter_GithubAll5593821360 ns/op0 B/op0 allocs/op
BenchmarkHttpTreeMux_GithubAll10000153944 ns/op65856 B/op671 allocs/op
BenchmarkKocha_GithubAll10000106315 ns/op23304 B/op843 allocs/op
BenchmarkLARS_GithubAll4777925084 ns/op0 B/op0 allocs/op
BenchmarkMacaron_GithubAll3266371907 ns/op149409 B/op1624 allocs/op
BenchmarkMartini_GithubAll3313444706 ns/op226551 B/op2325 allocs/op
BenchmarkPat_GithubAll2734381818 ns/op1483152 B/op26963 allocs/op
BenchmarkPossum_GithubAll10000164367 ns/op84448 B/op609 allocs/op
BenchmarkR2router_GithubAll10000160220 ns/op77328 B/op979 allocs/op
BenchmarkRivet_GithubAll1462582453 ns/op16272 B/op167 allocs/op
BenchmarkTango_GithubAll6255279611 ns/op63826 B/op1618 allocs/op
BenchmarkTigerTonic_GithubAll2008687874 ns/op193856 B/op4474 allocs/op
BenchmarkTraffic_GithubAll3553478508 ns/op820744 B/op14114 allocs/op
BenchmarkVulcan_GithubAll6885193333 ns/op19894 B/op609 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

  1. Check out our CONTRIBUTING.md for detailed guidelines
  2. Join our community discussions and ask questions

All contributions are valued and help make Gin better for everyone!