Gin Web Framework Examples
repository·master·Indexed 26 days ago
https://github.com/gin-gonic/examplesA 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.
What's inside gin-gonic-examples
- This repository provides a collection of ready-to-run examples demonstrating various use cases for the Gin web framework. Examples include OTEL integration, gRPC, Form Binding, and OIDC GitHub OAuth. To execute these examples, refer to the official Gin documentation.
Use the WebSocket Client
masterThe client connects to the server's/echoendpoint. It is designed to send periodic messages to the server and log any incoming responses from the server to the console.Use the WebSocket Echo Server
masterThe 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
8080by default.Group routes in Gin
masterYou can organize your API by grouping routes into logical segments (e.g., versioned APIs like
/v1or/v2) using therouter.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) }Set up the WebSocket Example
masterTo run the WebSocket demonstration, clone the repository, install the Go dependencies, and run the server and client in separate terminals.Implement graceful shutdown using the Close method
masterYou 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 (likeCtrl+C) is received.Setup and Execution
- Install Gin:
go get -u github.com/gin-gonic/gin- Run the server implementation:
go run server.go- Trigger shutdown by sending an interrupt signal (e.g.,
Ctrl+Cin the terminal).
Setup and Run New Relic Gin Example
masterFollow these steps to set up and run the New Relic integration example locally:
- Clone and Navigate:
git clone https://github.com/your-repo/gin-examples.git cd gin-examples/new_relic - Install Dependencies:
go mod tidy - Configure Environment Variables:
export NEW_RELIC_APP_NAME="YourAppName" export NEW_RELIC_LICENSE_KEY="YourNewRelicLicenseKey" - 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- Clone and Navigate:
Implement graceful shutdown without Context
masterTo implement a graceful shutdown using a channel to listen for interrupt signals instead of a context, use the
notify-without-contextpattern. This approach uses a channel to catch signals and then callsserver.Shutdown()with a specific timeout context to stop the server.Setup and Execution
- Install dependencies:
go get -u github.com/gin-gonic/gin- Run the server:
go run notify-without-context/server.goAccess the server at
http://localhost:8080/.Trigger shutdown by sending an interrupt signal (e.g.,
Ctrl+Cin the terminal).
go get -u github.com/gin-gonic/gin go run notify-without-context/server.goGenerate RSA private key and digital certificate for HTTP/2
masterTo use HTTP/2 with Gin, you need an RSA private key and a digital certificate. Follow these steps using OpenSSL:
- Install OpenSSL: Download and install the package from https://github.com/openssl/openssl.
- Generate RSA private key: Create a directory named
testdataand generate a 2048-bit RSA key. - 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 365Integrate OpenTelemetry (OTEL) with Gin
masterTo integrate OpenTelemetry with the Gin web framework for tracing HTTP requests, use the
otelginmiddleware. This allows you to capture trace IDs and span IDs for incoming requests.Prerequisites
- Go 1.23 or later
- Git
Dependencies
- Gin v1.10.0
- OpenTelemetry v1.35.0
- OTEL Gin Middleware v0.60.0
Configuration
When implementing this integration, ensure you handle context correctly. The example uses
ContextWithFallback = trueto enable OTEL within Gin, though you should evaluate if this is suitable for your specific production requirements.Embed static files and templates using //go:embed
masterYou can embed entire directories into your Go binary using the
//go:embeddirective and access them via theembed.FStype. This allows you to distribute a single binary containing all assets (images, icons) and templates.To use this with Gin:
- Use
//go:embedto declare anembed.FSvariable. - Use
template.ParseFSto load embedded HTML templates. - Use
router.StaticFSto serve embedded files via a URL prefix. - Use
f.ReadFileto manually serve specific embedded files (like favicons) viac.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") }- Use
Install Gin web framework
masterTo use Gin for form binding and validation, ensure you have Go 1.13+ installed and then install the Gin framework using
go get.go get -u github.com/gin-gonic/gin