Convert Figma logo to code with AI

gin-gonic logogin

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.

77,851
7,961
77,851
793

Top Related Projects

29,410

High performance, minimalist Go web framework

33,019

⚡️ Express inspired web framework written in Go

A high performance HTTP request router that scales well

20,665

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

18,066

lightweight, idiomatic and composable router for building Go HTTP services

21,607

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

29,410

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.

33,019

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

20,665

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.

18,066

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.

21,607

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 codecov Go Report Card Go Reference Sourcegraph Open Source Helpers Release TODOs

Gin is a web framework written in Go. It features a martini-like API with performance that is up to 40 times faster thanks to httprouter. If you need performance and good productivity, you will love Gin.

Gin's key features are:

  • Zero allocation router
  • Speed
  • Middleware support
  • Crash-free
  • JSON validation
  • Route grouping
  • Error management
  • Built-in rendering
  • Extensible

Getting started

Prerequisites

Gin requires Go version 1.21 or above.

Getting Gin

With Go's module support, go [build|run|test] automatically fetches the necessary dependencies when you add the import in your code:

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

Alternatively, use go get:

go get -u github.com/gin-gonic/gin

Running Gin

A basic example:

package main

import (
  "net/http"

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

func main() {
  r := gin.Default()
  r.GET("/ping", func(c *gin.Context) {
    c.JSON(http.StatusOK, gin.H{
      "message": "pong",
    })
  })
  r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

To run the code, use the go run command, like:

$ go run example.go

Then visit 0.0.0.0:8080/ping in your browser to see the response!

See more examples

Quick Start

Learn and practice with the Gin Quick Start, which includes API examples and builds tag.

Examples

A number of ready-to-run examples demonstrating various use cases of Gin are available in the Gin examples repository.

Documentation

See the API documentation on go.dev.

The documentation is also available on gin-gonic.com in several languages:

Articles

Benchmarks

Gin uses a custom version of HttpRouter, see all benchmarks.

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

You can find many useful Gin middlewares at gin-contrib.

Uses

Here are some awesome projects that are using the Gin web framework.

  • gorush: A push notification server.
  • fnproject: A container native, cloud agnostic serverless platform.
  • photoprism: Personal photo management powered by Google TensorFlow.
  • lura: Ultra performant API Gateway with middleware.
  • picfit: An image resizing server.
  • dkron: Distributed, fault tolerant job scheduling system.

Contributing

Gin is the work of hundreds of contributors. We appreciate your help!

Please see CONTRIBUTING.md for details on submitting patches and the contribution workflow.