Categorygithub.com/gin-gonic/gin
modulepackage
1.10.0
Repository: https://github.com/gin-gonic/gin.git
Documentation: pkg.go.dev

# README

Gin Web Framework

Build Status codecov Go Report Card GoDoc 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.

The key features of Gin are:

  • Zero allocation router
  • Fast
  • Middleware support
  • Crash-free
  • JSON validation
  • Routes grouping
  • Error management
  • Rendering built-in
  • Extendable

Getting started

Prerequisites

  • Go: any one of the three latest major releases (we test it with these).

Getting Gin

With Go module support, simply add the following import

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

to your code, and then go [build|run|test] will automatically fetch the necessary dependencies.

Otherwise, run the following Go command to install the gin package:

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

Running Gin

First you need to import Gin package for using Gin, one simplest example likes the follow example.go:

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")
}

And use the Go command to run the demo:

# run example.go and visit 0.0.0.0:8080/ping on browser
$ go run example.go

Learn more examples

Quick Start

Learn and practice more examples, please read 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 on the Gin examples repository.

Documentation

See API documentation and descriptions for package.

All documentation is available on the Gin website.

Articles about Gin

A curated list of awesome Gin framework.

Benchmarks

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

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

Middlewares

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

Users

Awesome project lists using Gin web framework.

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

Contributing

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

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

# Packages

# Functions

BasicAuth returns a Basic HTTP Authorization middleware.
BasicAuthForProxy returns a Basic HTTP Proxy-Authorization middleware.
BasicAuthForRealm returns a Basic HTTP Authorization middleware.
Bind is a helper function for given interface object and returns a Gin middleware.
CreateTestContext returns a fresh engine and context for testing purposes.
CreateTestContextOnly returns a fresh context base on the engine for testing purposes.
CustomRecovery returns a middleware that recovers from any panics and calls the provided handle func to handle it.
CustomRecoveryWithWriter returns a middleware for a given writer that recovers from any panics and calls the provided handle func to handle it.
Default returns an Engine instance with the Logger and Recovery middleware already attached.
Dir returns a http.FileSystem that can be used by http.FileServer().
DisableBindValidation closes the default validator.
DisableConsoleColor disables color output in the console.
EnableJsonDecoderDisallowUnknownFields sets true for binding.EnableDecoderDisallowUnknownFields to call the DisallowUnknownFields method on the JSON Decoder instance.
EnableJsonDecoderUseNumber sets true for binding.EnableDecoderUseNumber to call the UseNumber method on the JSON Decoder instance.
ErrorLogger returns a HandlerFunc for any error type.
ErrorLoggerT returns a HandlerFunc for a given error type.
ForceConsoleColor force color output in the console.
IsDebugging returns true if the framework is running in debug mode.
Logger instances a Logger middleware that will write the logs to gin.DefaultWriter.
LoggerWithConfig instance a Logger middleware with config.
LoggerWithFormatter instance a Logger middleware with the specified log format function.
LoggerWithWriter instance a Logger middleware with the specified writer buffer.
Mode returns current gin mode.
New returns a new blank Engine instance without any middleware attached.
Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.
RecoveryWithWriter returns a middleware for a given writer that recovers from any panics and writes a 500 if there was one.
SetMode sets gin mode according to input string.
WrapF is a helper function for wrapping http.HandlerFunc and returns a Gin middleware.
WrapH is a helper function for wrapping http.Handler and returns a Gin middleware.

# Constants

AuthProxyUserKey is the cookie name for proxy_user credential in basic auth for proxy.
AuthUserKey is the cookie name for user credential in basic auth.
BindKey indicates a default bind key.
BodyBytesKey indicates a default body bytes key.
ContextKey is the key that a Context returns itself for.
DebugMode indicates gin mode is debug.
EnvGinMode indicates environment name for gin mode.
ErrorTypeAny indicates any other error.
ErrorTypeBind is used when Context.Bind() fails.
ErrorTypeNu indicates any other error.
ErrorTypePrivate indicates a private error.
ErrorTypePublic indicates a public error.
ErrorTypeRender is used when Context.Render() fails.
Content-Type MIME of the most common data formats.
Content-Type MIME of the most common data formats.
Content-Type MIME of the most common data formats.
Content-Type MIME of the most common data formats.
Content-Type MIME of the most common data formats.
Content-Type MIME of the most common data formats.
Content-Type MIME of the most common data formats.
Content-Type MIME of the most common data formats.
Content-Type MIME of the most common data formats.
PlatformCloudflare when using Cloudflare's CDN.
PlatformFlyIO when running on Fly.io.
PlatformGoogleAppEngine when running on Google App Engine.
ReleaseMode indicates gin mode is release.
TestMode indicates gin mode is test.
Version is the current gin framework's version.

# Variables

DebugPrintFunc indicates debug log output format.
DebugPrintRouteFunc indicates debug log output format.
DefaultErrorWriter is the default io.Writer used by Gin to debug errors.
DefaultWriter is the default io.Writer used by Gin for debug output and middleware output like Logger() or Recovery().

# Structs

Context is the most important part of gin.
Engine is the framework's instance, it contains the muxer, middleware and configuration settings.
Error represents a error's specification.
LogFormatterParams is the structure any formatter will be handed when time to log comes.
LoggerConfig defines the config for Logger middleware.
Negotiate contains all negotiations data.
Param is a single URL parameter, consisting of a key and a value.
RouteInfo represents a request route's specification which contains method and path and its handler.
RouterGroup is used internally to configure router, a RouterGroup is associated with a prefix and an array of handlers (middleware).

# Interfaces

IRouter defines all router handle interface includes single and group router.
IRoutes defines all router handle interface.
ResponseWriter ...

# Type aliases

Accounts defines a key/value for user/pass list of authorized logins.
ErrorType is an unsigned 64-bit error code as defined in the gin spec.
H is a shortcut for map[string]any.
HandlerFunc defines the handler used by gin middleware as return value.
HandlersChain defines a HandlerFunc slice.
LogFormatter gives the signature of the formatter function passed to LoggerWithFormatter.
OptionFunc defines the function to change the default configuration.
Params is a Param-slice, as returned by the router.
RecoveryFunc defines the function passable to CustomRecovery.
RoutesInfo defines a RouteInfo slice.
Skipper is a function to skip logs based on provided Context.