Gin Web Framework Examples

repository·master·Indexed 26 days ago

https://github.com/gin-gonic/examples

A collection of ready-to-run code examples for the Gin web framework. Demonstrations include integration patterns such as CORS middleware, cookie management, form binding and validation, route grouping, graceful shutdown, gRPC integration, HTTP/2 setup, and embedding static files and templates using //go:embed.

Tokens
26.9K
Snippets
88
Records
126
Agent score
88%

What's inside gin-gonic-examples

  1. Use the WebSocket Echo Server

    master

    The WebSocket server uses the Gin framework and the Gorilla WebSocket library. It provides two primary endpoints:

    • /echo: Upgrades the HTTP connection to a WebSocket connection and echoes any received messages back to the client.
    • /: Serves an HTML page used for testing the WebSocket connection.

    The server listens on port 8080 by default.

  2. Group routes in Gin

    master

    You can organize your API by grouping routes into logical segments (e.g., versioned APIs like /v1 or /v2) using the router.Group() method. This allows you to modularize your routing logic by passing the group instance to separate functions that define specific sets of routes.

    func getRoutes() {
    	v1 := router.Group("/v1")
    	addUserRoutes(v1)
    	addPingRoutes(v1)
    
    	v2 := router.Group("/v2")
    	addPingRoutes(v2)
    }
  3. Implement graceful shutdown using the Close method

    master

    You can implement a graceful shutdown in a Gin server by using the server.Close() method. This ensures that the server completes any ongoing requests before shutting down when an interrupt signal (like Ctrl+C) is received.

    Setup and Execution

    1. Install Gin:
    go get -u github.com/gin-gonic/gin
    1. Run the server implementation:
    go run server.go
    1. Trigger shutdown by sending an interrupt signal (e.g., Ctrl+C in the terminal).
  4. Setup and Run New Relic Gin Example

    master

    Follow these steps to set up and run the New Relic integration example locally:

    1. Clone and Navigate:
      git clone https://github.com/your-repo/gin-examples.git
      cd gin-examples/new_relic
    2. Install Dependencies:
      go mod tidy
    3. Configure Environment Variables:
      export NEW_RELIC_APP_NAME="YourAppName"
      export NEW_RELIC_LICENSE_KEY="YourNewRelicLicenseKey"
    4. Run the Application:
      go run main.go

    The server will start on http://localhost:8080.

    git clone https://github.com/your-repo/gin-examples.git
    cd gin-examples/new_relic
    go mod tidy
    export NEW_RELIC_APP_NAME="YourAppName"
    export NEW_RELIC_LICENSE_KEY="YourNewRelicLicenseKey"
    go run main.go
  5. Implement graceful shutdown without Context

    master

    To implement a graceful shutdown using a channel to listen for interrupt signals instead of a context, use the notify-without-context pattern. This approach uses a channel to catch signals and then calls server.Shutdown() with a specific timeout context to stop the server.

    Setup and Execution

    1. Install dependencies:
    go get -u github.com/gin-gonic/gin
    1. Run the server:
    go run notify-without-context/server.go
    1. Access the server at http://localhost:8080/.

    2. Trigger shutdown by sending an interrupt signal (e.g., Ctrl+C in the terminal).

    go get -u github.com/gin-gonic/gin
    go run notify-without-context/server.go
  6. Generate RSA private key and digital certificate for HTTP/2

    master

    To use HTTP/2 with Gin, you need an RSA private key and a digital certificate. Follow these steps using OpenSSL:

    1. Install OpenSSL: Download and install the package from https://github.com/openssl/openssl.
    2. Generate RSA private key: Create a directory named testdata and generate a 2048-bit RSA key.
    3. Generate digital certificate: Create a self-signed certificate valid for 365 days using the generated key.
    $ mkdir testdata
    $ openssl genrsa -out ./testdata/server.key 2048
    $ openssl req -new -x509 -key ./testdata/server.key -out ./testdata/server.pem -days 365
  7. Integrate OpenTelemetry (OTEL) with Gin

    master

    To integrate OpenTelemetry with the Gin web framework for tracing HTTP requests, use the otelgin middleware. This allows you to capture trace IDs and span IDs for incoming requests.

    Prerequisites

    • Go 1.23 or later
    • Git

    Dependencies

    Configuration

    When implementing this integration, ensure you handle context correctly. The example uses ContextWithFallback = true to enable OTEL within Gin, though you should evaluate if this is suitable for your specific production requirements.

  8. Embed static files and templates using //go:embed

    master

    You can embed entire directories into your Go binary using the //go:embed directive and access them via the embed.FS type. This allows you to distribute a single binary containing all assets (images, icons) and templates.

    To use this with Gin:

    1. Use //go:embed to declare an embed.FS variable.
    2. Use template.ParseFS to load embedded HTML templates.
    3. Use router.StaticFS to serve embedded files via a URL prefix.
    4. Use f.ReadFile to manually serve specific embedded files (like favicons) via c.Data.
    //go:embed assets/* templates/*
    var f embed.FS
    
    func main() {
      router := gin.Default()
      
      // Load templates from embedded FS
      templ := template.Must(template.New("").ParseFS(f, "templates/*.tmpl", "templates/foo/*.tmpl"))
      router.SetHTMLTemplate(templ)
    
      // Serve embedded assets under the /public path
      router.StaticFS("/public", http.FS(f))
    
      router.GET("/", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.tmpl", gin.H{
          "title": "Main website",
        })
      })
    
      // Manually serving a specific embedded file
      router.GET("favicon.ico", func(c *gin.Context) {
        file, _ := f.ReadFile("assets/favicon.ico")
        c.Data(
          http.StatusOK,
          "image/x-icon",
          file,
        )
      })
    
      router.Run(":8080")
    }