Gin Web Framework

website·Indexed 36 days ago

https://gin-gonic.com

A high-performance HTTP web framework for Go. Gin provides a powerful routing system, middleware support, data binding with validation via go-playground/validator, and flexible rendering options for JSON, HTML templates, and static files. It includes built-in logging and recovery middleware, and supports advanced configurations such as WebSocket integration, Let's Encrypt via autotls, and HTTP/3 in version 1.11.0.

Tokens
47K
Snippets
217
Records
310
Agent score
70%

What's inside Gin

  1. Overview of the Gin Web Framework

    Gin is a high-performance HTTP web framework written in Go. It features a Radix tree-based routing mechanism, a small memory footprint, and avoids the use of reflection to ensure predictable API performance.
  2. Overview of the Gin Web Framework

    Gin is a high-performance web framework written in Go (Golang) designed for productivity and speed. It utilizes a martini-like API but achieves significantly higher performance (up to 40 times faster) by leveraging a radix tree-based router (httprouter). Key characteristics include a small memory footprint, no use of reflection, and predictable API performance.
  3. Overview of the Gin Web Framework

    Gin is a high-performance HTTP web framework for Go, designed for building REST APIs, microservices, and web applications. It features a zero-allocation router based on httprouter, providing significantly better performance than Martini. Key capabilities include built-in recovery middleware to prevent server crashes, automatic JSON validation and binding, route grouping, and support for multiple rendering formats (JSON, XML, HTML).
  4. Overview of Gin Web Framework

    Gin is a high-performance HTTP web framework written in Go. It features a Radix tree-based routing system for fast request handling, maintains a small memory footprint, avoids the use of reflection to ensure predictable API performance, and provides a fast execution environment.
  5. Integrate WebSockets in Gin using gorilla/websocket

    Gin does not have a built-in WebSocket implementation. It integrates with the gorilla/websocket package by using the underlying http.ResponseWriter and *http.Request provided in Gin handlers to upgrade HTTP connections to WebSocket connections.
    go get github.com/gorilla/websocket
  6. Bind request data into Go structs using Gin

    Gin provides a binding system that automatically parses request data (JSON, XML, YAML, TOML, form data, query strings, URI parameters, and headers) into Go structs. Mapping is handled via struct tags (e.g., json, xml, form, uri, header), and validation is performed using the binding tag, which follows the go-playground/validator syntax.
  7. Learn Go language fundamentals for Gin development

    To effectively use Gin, developers should be familiar with Go idiomatic patterns and the standard library. Recommended resources include 'A Tour of Go' for an interactive introduction, 'Effective Go' for best practices, 'Go by Example' for annotated fundamentals, and the Go Standard Library documentation (specifically net/http, which Gin is built upon).
    A Tour of Go: https://go.dev/tour/
    Effective Go: https://go.dev/doc/effective%5Fgo
    Go by Example: https://gobyexample.com/
    Go Std Lib: https://pkg.go.dev/std
  8. Use BSON and Protocol Buffers in Gin v1.12.0

    Gin v1.12.0 introduces support for BSON encoding in the render layer for efficient binary data exchange. Additionally, the context now supports Protocol Buffers as a negotiable content type, facilitating easier integration of gRPC-style responses.
  9. Understand the Gin middleware execution model

    Gin middleware follows an 'onion model' where each middleware function (with the signature gin.HandlerFunc) can execute code both before and after the main route handler. Control is passed to the next handler in the chain using c.Next(). Code appearing before c.Next() is the pre-handler phase, and code appearing after is the post-handler phase.
    func Logger() gin.HandlerFunc {
        return func(c *gin.Context) {
            start := time.Now()
            
            // Pre-handler phase: runs before the route handler
            c.Next()
            
            // Post-handler phase: runs after the route handler returns
            latency := time.Since(start)
            log.Printf("Request took %v", latency)
        }
    }
  10. Initialize a Gin router with default middleware using gin.Default()

    gin.Default() creates a router engine with two built-in middleware components already attached:

    1. Logger: Logs request details (method, path, status code, and latency) to stdout.
    2. Recovery: Recovers from panics within handlers to prevent the server from crashing and returns a 500 Internal Server Error response.
    router := gin.Default()
  11. Render responses in JSON, XML, YAML, or ProtoBuf

    Gin provides built-in methods to serialize data and automatically set the appropriate Content-Type header for various formats. Each rendering method requires an HTTP status code and the data object to be serialized.

    • JSON: Use c.JSON() for standard REST APIs or c.IndentedJSON() for human-readable output during development.
    • XML: Use c.XML() for legacy systems or SOAP services.
    • YAML: Use c.YAML() for configuration-oriented endpoints.
    • ProtoBuf: Use c.ProtoBuf() for high-performance, low-latency service communication (requires a shared .proto schema).
    package main
    
    import (
    	"net/http"
    	"github.com/gin-gonic/gin"
    	"github.com/gin-gonic/gin/testdata/protoexample"
    )
    
    func main() {
    	router := gin.Default()
    
    	// Render JSON using gin.H (shortcut for map[string]interface{})
    	router.GET("/someJSON", func(c *gin.Context) {
    		c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
    	})
    
    	// Render JSON using a struct with tags
    	router.GET("/moreJSON", func(c *gin.Context) {
    		var msg struct {
    			Name    string `json:"user"`
    			Message string
    			Number  int
    		}
    		msg.Name = "Lena"
    		msg.Message = "hey"
    		msg.Number = 123
    		c.JSON(http.StatusOK, msg)
    	})
    
    	// Render XML
    	router.GET("/someXML", func(c *gin.Context) {
    		c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
    	})
    
    	// Render YAML
    	router.GET("/someYAML", func(c *gin.Context) {
    		c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
    	})
    
    	// Render Protocol Buffers (binary data)
    	router.GET("/someProtoBuf", func(c *gin.Context) {
    		reps := []int64{int64(1), int64(2)}
    		label := "test"
    		data := &protoexample.Test{
    			Label: &label,
    			Reps:  reps,
    		}
    		c.ProtoBuf(http.StatusOK, data)
    	})
    
    	router.Run(":8080")
    }