### Install Gin Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/QUICK_START.md Use go get to install the Gin framework. ```bash go get github.com/gin-gonic/gin ``` -------------------------------- ### Create First Gin Application Source: https://github.com/gin-gonic/gin/blob/master/README.md A basic example demonstrating how to create a Gin router with default middleware, define a GET endpoint, and start the server. This snippet includes logger and recovery middleware by default. ```go package main import ( "log" "net/http" "github.com/gin-gonic/gin" ) func main() { // Create a Gin router with default middleware (logger and recovery) r := gin.Default() // Define a simple GET endpoint r.GET("/ping", func(c *gin.Context) { // Return JSON response c.JSON(http.StatusOK, gin.H{ "message": "pong", }) }) // Start server on port 8080 (default) // Server will listen on 0.0.0.0:8080 (localhost:8080 on Windows) if err := r.Run(); err != nil { log.Fatalf("failed to run server: %v", err) } } ``` -------------------------------- ### Start Gin Server Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/QUICK_START.md Provides examples of how to start the Gin server, including using the default port, a custom port, with TLS, via a Unix socket, or with a custom listener. ```go // Default: :8080 router.Run() // Custom port router.Run(":3000") // With TLS router.RunTLS(":443", "cert.pem", "key.pem") // Unix socket router.RunUnix("/tmp/gin.sock") // Custom listener listener, _ := net.Listen("tcp", ":8080") router.RunListener(listener) ``` -------------------------------- ### Install Gin Framework Source: https://github.com/gin-gonic/gin/wiki/Run-Gin-web-framework-on-Android Use 'go get' to install the Gin framework. This command fetches and installs the specified package and its dependencies. ```bash go get github.com/gin-gonic/gin ``` -------------------------------- ### Basic Gin Server Setup Source: https://github.com/gin-gonic/gin/blob/master/ginS/README.md Sets up a simple Gin server with a root route that returns 'Hello World'. Ensure Gin is installed and imported correctly. ```go package main import ( "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/ginS" ) func main() { ginS.GET("/", func(c *gin.Context) { c.String(200, "Hello World") }) ginS.Run() } ``` -------------------------------- ### Param Example Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/types.md Illustrates how a Param is structured for a route like GET /users/:id with a request to /users/123. ```Go // For route: GET /users/:id // Request: GET /users/123 // Param: {Key: "id", Value: "123"} ``` -------------------------------- ### BindUri Example Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/types.md Example demonstrating how to use BindUri to bind URL path parameters into a struct. Ensure the struct fields have the correct `uri` tags. ```go type IDRequest struct { ID string `uri:"id" binding:"required"` } var req IDRequest c.BindUri(&req) ``` -------------------------------- ### Complete Gin Binding Example Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/binding.md Shows a comprehensive example of binding JSON, query, and URI parameters in Gin routes, including validation rules. ```go // Request struct with comprehensive binding and validation type CreateUserRequest struct { // JSON binding with validation Name string `json:"name" binding:"required,min=2,max=50" Email string `json:"email" binding:"required,email" Age int `json:"age" binding:"required,gte=18,lte=120" Password string `json:"password" binding:"required,min=8,max=100" Website string `json:"website" binding:"omitempty,url" } type PageQuery struct { Page int `form:"page" binding:"omitempty,gte=1" Limit int `form:"limit" binding:"omitempty,gte=1,lte=100" Sort string `form:"sort" binding:"omitempty,oneof=asc desc" } type UserIDPath struct { ID string `uri:"id" binding:"required,uuid" } router := gin.Default() // Create user with JSON binding router.POST("/users", func(c *gin.Context) { var req CreateUserRequest if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, gin.H{"error": err.Error()}) return } c.JSON(201, gin.H{"id": 1, "email": req.Email}) }) // List with query binding router.GET("/users", func(c *gin.Context) { var query PageQuery if err := c.ShouldBindQuery(&query); err != nil { c.JSON(400, gin.H{"error": err.Error()}) return } c.JSON(200, gin.H{"page": query.Page, "limit": query.Limit}) }) // Get user with URI binding router.GET("/users/:id", func(c *gin.Context) { var path UserIDPath if err := c.BindUri(&path); err != nil { c.JSON(400, gin.H{"error": err.Error()}) return } c.JSON(200, gin.H{"id": path.ID}) }) ``` -------------------------------- ### Start Gin Server Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/INDEX.md Run the Gin server on a specified port. This method is blocking and will start the HTTP server. ```go router.Run(":8080") ``` -------------------------------- ### Gin Rendering Examples Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/rendering.md This snippet shows how to render various response types using the Gin framework. It includes examples for JSON, XML, HTML, plain text, file downloads, redirects, and content negotiation. ```Go router := gin.Default() // JSON router.GET("/json", func(c *gin.Context) { c.JSON(200, gin.H{"message": "hello"}) }) // XML router.GET("/xml", func(c *gin.Context) { c.XML(200, gin.H{"message": "hello"}) }) // HTML router.LoadHTMLGlob("templates/*.html") router.GET("/html", func(c *gin.Context) { c.HTML(200, "index.html", gin.H{"title": "Home"}) }) // Plain text router.GET("/text", func(c *gin.Context) { c.String(200, "Hello %s", "World") }) // File download router.GET("/download", func(c *gin.Context) { c.FileAttachment("/path/to/file.pdf", "document.pdf") }) // Redirect router.GET("/old", func(c *gin.Context) { c.Redirect(301, "/new") }) // Content negotiation router.GET("/api", func(c *gin.Context) { c.Negotiate(200, gin.Negotiate{ Offered: []string{gin.MIMEJSON, gin.MIMEXML}, Data: gin.H{"id": 1}, }) }) ``` -------------------------------- ### Run Gin Server Source: https://github.com/gin-gonic/gin/blob/master/docs/doc.md Start the Gin web server to listen for incoming requests on the specified port. ```go router.Run(":8080") ``` -------------------------------- ### Apply Configuration Options with With Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/configuration.md Applies a variadic list of configuration functions to the Engine. This allows for flexible and modular configuration setup. ```go engine := gin.New().With( func(e *gin.Engine) { e.MaxMultipartMemory = 64 << 20 e.HandleMethodNotAllowed = true }, ) ``` -------------------------------- ### With Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/configuration.md Applies a variadic list of configuration functions to the Engine, allowing for flexible and modular setup. ```APIDOC ## With ### Description Applies configuration functions to the Engine. ### Method `func (engine *Engine) With(opts ...OptionFunc) *Engine` ### Parameters - **opts** (`...OptionFunc`) - Required - Configuration functions ### Returns `*Engine` - The configured Engine ### Example ```go engine := gin.New().With( func(e *gin.Engine) { e.MaxMultipartMemory = 64 << 20 e.HandleMethodNotAllowed = true }, ) ``` ``` -------------------------------- ### RunListener Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/engine.md Starts the server with a custom `net.Listener`. This allows for advanced network configurations. ```APIDOC ## RunListener ### Description Starts the server with a custom `net.Listener`. ### Method `RunListener` ### Parameters #### Path Parameters - **listener** (`net.Listener`) - Required - Custom listener ### Returns `error` - Server error if any ### Example ```go listener, _ := net.Listen("tcp", ":8080") engine.RunListener(listener) ``` ``` -------------------------------- ### Register GET Route Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/routergroup.md Registers a GET route with optional middleware and a main handler. This example shows both a top-level route and routes within a group. ```go router.GET("/ping", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "pong"}) }) api := router.Group("/api") api.GET("/users", listUsers) api.GET("/users/:id", getUser) api.GET("/users/:id/posts", authMiddleware, getUserPosts) ``` -------------------------------- ### ErrorType Example Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/types.md Example showing how to set and check error types using bitmasks. Useful for conditional error handling. ```go err := c.Error(errors.New("validation failed")) err.SetType(gin.ErrorTypePublic) if err.IsType(gin.ErrorTypePublic) { c.JSON(400, err.JSON()) } ``` -------------------------------- ### Create and Use HandlerFunc Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/types.md Example of defining a HandlerFunc and assigning it to a route. ```Go func myHandler(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "ok"}) } router.GET("/path", myHandler) ``` -------------------------------- ### Run HTTP Server Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/engine.md Use the Run method to start the HTTP server, listening on a specified address. It defaults to :8080 if no address is provided. ```go if err := engine.Run(":3000"); err != nil { log.Fatal(err) } ``` -------------------------------- ### Error JSON Method Example Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/types.md Example demonstrating how to set metadata on an error and retrieve its JSON representation. ```go err := c.Error(errors.New("not found")) err.SetMeta(gin.H{"code": "ERR_NOT_FOUND"}) jSONData := err.JSON() ``` -------------------------------- ### Setup Gin Router for Testing Source: https://github.com/gin-gonic/gin/blob/master/docs/doc.md Defines a basic Gin router with a /ping endpoint that returns 'pong'. This setup is used for testing purposes. ```go package main import ( "net/http" "github.com/gin-gonic/gin" ) func setupRouter() *gin.Engine { r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong") }) return r } func main() { r := setupRouter() r.Run(":8080") } ``` -------------------------------- ### Run Server with Custom Listener Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/engine.md Starts the Gin server using a pre-configured net.Listener. This allows for custom network configurations. ```go listener, _ := net.Listen("tcp", ":8080") engine.RunListener(listener) ``` -------------------------------- ### Run Server on Unix Socket Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/engine.md Starts the Gin server on a Unix socket. Provide the path to the socket file as a string. ```go if err := engine.RunUnix("/tmp/gin.sock"); err != nil { log.Fatal(err) } ``` -------------------------------- ### Run Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/engine.md Attaches the router to an `http.Server` and starts listening and serving HTTP requests. By default, listens on `:8080` unless `PORT` environment variable is set. ```APIDOC ## Run ### Description Attaches the router to an `http.Server` and starts listening and serving HTTP requests. By default, listens on `:8080` unless `PORT` environment variable is set. ### Method `Run` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go if err := engine.Run(":3000"); err != nil { log.Fatal(err) } ``` ### Response #### Success Response `error` - Server error if any #### Response Example None ``` -------------------------------- ### Run HTTPS Server with TLS Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/engine.md Start an HTTPS server using RunTLS, which requires the address and paths to the TLS certificate and key files. ```go if err := engine.RunTLS(":443", "cert.pem", "key.pem"); err != nil { log.Fatal(err) } ``` -------------------------------- ### Go Function Signature Example Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/README.md Illustrates the standard Go function signature format as documented. This shows the function name, parameter types, and return type. ```go func MethodName(param1 Type1, param2 Type2) ReturnType ``` -------------------------------- ### Run Gin Server Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/DOCUMENTATION_COMPLETE.txt Start the HTTP server using `Run`. Supports standard HTTP, HTTPS with TLS, or Unix sockets. ```Go r.Run() r.Run(":8080") r.RunTLS("8080", "cert.pem", "key.pem") r.RunUnix("/tmp/app.sock") ``` -------------------------------- ### Basic Gin Server Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/QUICK_START.md Sets up a default Gin router with logger and recovery middleware, defines a /ping route, and starts the server on port 8080. ```go package main import ( "net/http" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() // Includes Logger and Recovery middleware router.GET("/ping", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "message": "pong", }) }) router.Run(":8080") // Default port if not specified } ``` -------------------------------- ### Form Binding Usage Example Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/binding.md Demonstrates how to use the `Form` binding implementation to bind data from an HTTP request into a Go interface. ```go var obj interface{} binding.Form.Bind(c.Request, &obj) ``` -------------------------------- ### POST Form Binding Example Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/binding.md Demonstrates how to bind POST form data to a struct using `c.ShouldBind`. It includes error handling for binding failures. ```go router.POST("/submit", func(c *gin.Context) { var form SubmitForm if err := c.ShouldBind(&form); err != nil { c.JSON(400, gin.H{"error": err.Error()}) return } }) ``` -------------------------------- ### Define Basic Routes Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/QUICK_START.md Shows how to define routes for common HTTP methods (GET, POST, PUT, DELETE, PATCH) and custom methods like ANY or CUSTOM. ```go router.GET("/users", listUsers) router.POST("/users", createUser) router.PUT("/users/:id", updateUser) router.DELETE("/users/:id", deleteUser) router.PATCH("/users/:id", partialUpdate) // Match any method router.Any("/method-any", handler) // Custom HTTP method router.Handle("CUSTOM", "/path", handler) // Multiple methods router.Match([]string{"GET", "POST"}, "/data", handler) ``` -------------------------------- ### RunUnix Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/engine.md Starts the server on a Unix socket. This method is used to bind the server to a specific Unix domain socket file. ```APIDOC ## RunUnix ### Description Starts the server on a Unix socket. ### Method `RunUnix` ### Parameters #### Path Parameters - **file** (`string`) - Required - Unix socket file path ### Returns `error` - Server error if any ### Example ```go if err := engine.RunUnix("/tmp/gin.sock"); err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### RunTLS Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/engine.md Starts an HTTPS server with TLS/SSL certificates. Requires the address, certificate file path, and key file path. ```APIDOC ## RunTLS ### Description Starts an HTTPS server with TLS/SSL certificates. Requires the address, certificate file path, and key file path. ### Method `RunTLS` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go if err := engine.RunTLS(":443", "cert.pem", "key.pem"); err != nil { log.Fatal(err) } ``` ### Response #### Success Response `error` - Server error if any #### Response Example None ``` -------------------------------- ### Upload Files Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/QUICK_START.md Provides examples for handling single and multiple file uploads using Gin, including saving the uploaded files to disk. ```go // Single file file, err := c.FormFile("file") if err != nil { c.JSON(400, gin.H{"error": "no file"}) return } // Save file c.SaveUploadedFile(file, "/tmp/" + file.Filename) // Multiple files form, _ := c.MultipartForm() files := form.File["files"] for _, file := range files { c.SaveUploadedFile(file, "/tmp/" + file.Filename) } ``` -------------------------------- ### JSON BindingBody Example Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/binding.md Shows how to use the `JSON` binding implementation to bind raw JSON byte data into a Go interface. ```go jsonData := []byte(`{"name":"Alice"}`) var obj interface{} binding.JSON.BindBody(jsonData, &obj) ``` -------------------------------- ### Create a Default Gin Engine Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/engine.md Use `gin.Default()` to create an Engine instance with the Logger and Recovery middleware pre-attached. This is the most common way to start a Gin application. ```go router := gin.Default() router.GET("/users", listUsers) router.Run(":8080") ``` -------------------------------- ### Handling HTTP Methods in Gin Source: https://github.com/gin-gonic/gin/blob/master/docs/doc.md Demonstrates how to define handlers for common HTTP methods like GET, POST, PUT, DELETE, PATCH, HEAD, and OPTIONS using gin.Default(). ```go func main() { // Creates a gin router with default middleware: // logger and recovery (crash-free) middleware router := gin.Default() router.GET("/someGet", getting) router.POST("/somePost", posting) router.PUT("/somePut", putting) router.DELETE("/someDelete", deleting) router.PATCH("/somePatch", patching) router.HEAD("/someHead", head) router.OPTIONS("/someOptions", options) // By default, it serves on :8080 unless a // PORT environment variable was defined. router.Run() // router.Run(":3000") for a hard coded port } ``` -------------------------------- ### Run Multiple Services with Gin Source: https://github.com/gin-gonic/gin/blob/master/docs/doc.md This example demonstrates how to run multiple Gin services concurrently using Go's errgroup package. Each service is configured with its own HTTP server and port. ```go package main import ( "log" "net/http" "time" "github.com/gin-gonic/gin" "golang.org/x/sync/errgroup" ) var ( g errgroup.Group ) func router01() http.Handler { e := gin.New() e.Use(gin.Recovery()) e.GET("/", func(c *gin.Context) { c.JSON( http.StatusOK, gin.H{ "code": http.StatusOK, "error": "Welcome server 01", }, ) }) return e } func router02() http.Handler { e := gin.New() e.Use(gin.Recovery()) e.GET("/", func(c *gin.Context) { c.JSON( http.StatusOK, gin.H{ "code": http.StatusOK, "error": "Welcome server 02", }, ) }) return e } func main() { server01 := &http.Server{ Addr: ":8080", Handler: router01(), ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, } server02 := &http.Server{ Addr: ":8081", Handler: router02(), ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, } g.Go(func() error { err := server01.ListenAndServe() if err != nil && err != http.ErrServerClosed { log.Fatal(err) } return err }) g.Go(func() error { err := server02.ListenAndServe() if err != nil && err != http.ErrServerClosed { log.Fatal(err) } return err }) if err := g.Wait(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Create Default Engine in Gin Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/INDEX.md Use gin.Default() to create an Engine instance with Logger and Recovery middleware. This is a common starting point. ```go gin.Default() ``` -------------------------------- ### Create Default Gin Engine Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/configuration.md Initializes a Gin engine with default middleware like Logger and Recovery. This is a convenient starting point for most applications. ```go router := gin.Default() // Equivalent to: // router := gin.New() // router.Use(gin.Logger()) // router.Use(gin.Recovery()) ``` -------------------------------- ### Access Query Parameters in Gin Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/INDEX.md Get values from the URL query string using c.Query(). For example, /search?q=gin. ```go c.Query("q") ``` -------------------------------- ### Serve Static Files with Gin Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/QUICK_START.md Shows how to serve static files and directories using Gin's Static and StaticFS methods. This is useful for serving CSS, JavaScript, and images. ```go // Serve directory router.Static("/public", "./public") // /public/file.js serves ./public/file.js // Serve single file router.StaticFile("/favicon.ico", "./favicon.ico") // Using FileSystem router.StaticFS("/assets", http.Dir("./assets")) ``` -------------------------------- ### Get Query Parameters as Map Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/context.md Retrieves all query parameters that start with a specific prefix and returns them as a map. This is useful for grouping related query parameters. ```go filters := c.QueryMap("filter") ``` -------------------------------- ### Build a REST API with Gin Groups Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/routergroup.md This example demonstrates building a REST API by organizing routes into groups with different middleware and access levels. It shows how to create public, API versioned, and protected admin routes. ```Go router := gin.Default() // Public routes public := router.Group("/public") public.GET("/health", healthCheck) // API v1 routes api := router.Group("/api/v1") api.Use(requestLoggingMiddleware) // Protected routes protected := api.Group("/admin") protected.Use(authenticationMiddleware) protected.GET("/users", listUsers) protected.POST("/users", createUser) protected.PUT("/users/:id", updateUser) protected.DELETE("/users/:id", deleteUser) // Public API routes api.GET("/posts", listPosts) api.GET("/posts/:id", getPost) router.Run(":8080") ``` -------------------------------- ### Serve Data from File with Gin Source: https://github.com/gin-gonic/gin/blob/master/docs/doc.md Use c.File to serve a local file or c.FileFromFS to serve a file from an http.FileSystem. Ensure the file paths are correct and the http.FileSystem is properly initialized. ```go func main() { router := gin.Default() router.GET("/local/file", func(c *gin.Context) { c.File("local/file.go") }) var fs http.FileSystem = // ... router.GET("/fs/file", func(c *gin.Context) { c.FileFromFS("fs/file.go", fs) }) } ``` -------------------------------- ### Example Route Handler in Gin Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/README.md This snippet demonstrates a basic route handler for a GET request in Gin. It extracts a user ID from the URL parameters and returns it as a JSON response. ```go router.GET("/users/:id", func(c *gin.Context) { userID := c.Param("id") c.JSON(200, gin.H{"id": userID}) }) ``` -------------------------------- ### Multipart Form Binding and File Upload Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/binding.md Example of binding multipart form data, including file uploads, using `c.ShouldBind`. It also shows how to save the uploaded file. ```go type FileUpload struct { Name string `form:"name" binding:"required" File *multipart.FileHeader `form:"file" binding:"required" } router.POST("/upload", func(c *gin.Context) { var upload FileUpload if err := c.ShouldBind(&upload); err != nil { c.JSON(400, gin.H{"error": err.Error()}) return } if err := c.SaveUploadedFile(upload.File, "/tmp/file"); err != nil { c.JSON(500, gin.H{"error": "failed to save file"}) return } c.JSON(200, gin.H{"filename": upload.File.Filename}) }) ``` -------------------------------- ### Get Parameter by Name Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/types.md The Get method on Params retrieves a parameter's value by its name and indicates if it was found. ```Go params := gin.Params{ {Key: "id", Value: "123"}, {Key: "action", Value: "edit"}, } value, found := params.Get("id") // "123", true value, found := params.Get("none") // "", false ``` -------------------------------- ### Register a GET Route in Gin Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/INDEX.md Define a handler function for a specific HTTP GET request path. The handler receives a gin.Context object. ```go router.GET("/path", handler) ``` -------------------------------- ### Serve Static Files Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/DOCUMENTATION_COMPLETE.txt Configure Gin to serve static files from directories or file systems. Use `Static` for directories or `StaticFile` for single files. ```Go r.Static("/static", "./static") r.StaticFS("/assets", http.Dir("./assets")) r.StaticFile("/favicon.ico", "./favicon.ico") r.StaticFileFS("/robots.txt", "./public/robots.txt", http.Dir("./public")) ``` -------------------------------- ### Serve Static Files with Gin Source: https://github.com/gin-gonic/gin/blob/master/docs/doc.md Use router.Static and router.StaticFS to serve files from directories and router.StaticFile and router.StaticFileFS for individual files. Ensure the paths are correctly specified. ```go func main() { router := gin.Default() router.Static("/assets", "./assets") router.StaticFS("/more_static", http.Dir("my_file_system")) router.StaticFile("/favicon.ico", "./resources/favicon.ico") router.StaticFileFS("/more_favicon.ico", "more_favicon.ico", http.Dir("my_file_system")) // Listen and serve on 0.0.0.0:8080 router.Run(":8080") } ``` -------------------------------- ### Get Value from Context Storage (Panics if Not Found) Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/context.md Retrieves a value from the context's key-value store. This method panics if the specified key does not exist, unlike `Get`. ```go userID := c.MustGet("user_id").(int) ``` -------------------------------- ### GET Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/routergroup.md Registers a GET route. It accepts a relative path and a variadic list of handlers, where the last handler is the main handler and preceding ones are middleware for that specific route. ```APIDOC ## GET ### Description Registers a GET route. It accepts a relative path and a variadic list of handlers, where the last handler is the main handler and preceding ones are middleware for that specific route. ### Method `*RouterGroup.GET` ### Parameters #### Path Parameters - **relativePath** (string) - Required - Path relative to group base (e.g., "/users") - **handlers** (...HandlerFunc) - Optional - Handler and optional middleware ### Returns - `IRoutes` - The group for chaining ### Example ```go router.GET("/ping", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "pong"}) }) api := router.Group("/api") api.GET("/users", listUsers) api.GET("/users/:id", getUser) api.GET("/users/:id/posts", authMiddleware, getUserPosts) ``` ``` -------------------------------- ### Create Gin Engine Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/QUICK_START.md Demonstrates creating a Gin engine with default middleware, without middleware, or with custom configuration like MaxMultipartMemory. ```go // With default middleware (logger + recovery) router := gin.Default() // Without any middleware router := gin.New() // With configuration router := gin.New() router.MaxMultipartMemory = 64 << 20 // 64 MB ``` -------------------------------- ### Create a New Gin Engine Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/DOCUMENTATION_COMPLETE.txt Instantiate a new Gin engine. Use `Default()` for a pre-configured engine with basic middleware, or `New()` for a minimal instance. ```Go engine := gin.New() router := gin.Default() ``` -------------------------------- ### Curl Examples for Custom Validators Source: https://github.com/gin-gonic/gin/blob/master/docs/doc.md Illustrates how to test the custom validation logic for booking dates using curl commands. These examples show successful validation and cases where validation fails due to incorrect date order or past dates. ```console $ curl "localhost:8085/bookable?check_in=2030-04-16&check_out=2030-04-17" {"message":"Booking dates are valid!"} $ curl "localhost:8085/bookable?check_in=2030-03-10&check_out=2030-03-09" {"error":"Key: 'Booking.CheckOut' Error:Field validation for 'CheckOut' failed on the 'gtfield' tag"} $ curl "localhost:8085/bookable?check_in=2000-03-09&check_out=2000-03-10" {"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}% ``` -------------------------------- ### Example cURL Request for JSON Binding Source: https://github.com/gin-gonic/gin/blob/master/docs/doc.md Demonstrates how to send a POST request with a JSON payload to the `/loginJSON` endpoint. This example shows a case where the `Password` field is missing, triggering a validation error due to the `binding:"required"` tag. ```sh $ curl -v -X POST \ http://localhost:8080/loginJSON \ -H 'content-type: application/json' \ -d '{ "user": "manu" }' > POST /loginJSON HTTP/1.1 > Host: localhost:8080 > User-Agent: curl/7.51.0 > Accept: */* > content-type: application/json > Content-Length: 18 > * upload completely sent off: 18 out of 18 bytes < HTTP/1.1 400 Bad Request < Content-Type: application/json; charset=utf-8 < Date: Fri, 04 Aug 2017 03:51:31 GMT < Content-Length: 100 > {"error":"Key: 'Login.Password' Error:Field validation for 'Password' failed on the 'required' tag"} ``` -------------------------------- ### Get All Error Messages Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/errors.md Returns a slice of error messages as strings. ```go c.Error(errors.New("first")) c.Error(errors.New("second")) c.Error(errors.New("third")) messages := c.Errors.Errors() // ["first", "second", "third"] ``` -------------------------------- ### Configure Gin Server Settings Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/QUICK_START.md Illustrates how to configure various aspects of the Gin engine, including routing behavior, proxy settings, and multipart memory limits. ```go router := gin.New() // Routing config router.RedirectTrailingSlash = true router.RedirectFixedPath = false router.HandleMethodNotAllowed = true // Proxy config router.ForwardedByClientIP = true router.RemoteIPHeaders = []string{"X-Forwarded-For", "X-Real-IP"} router.TrustedPlatform = gin.PlatformCloudflare // Multipart config router.MaxMultipartMemory = 64 << 20 // 64 MB // HTML templates router.Delims("{%", "%}") router.SecureJsonPrefix("while(1);") ``` -------------------------------- ### Get Last Error Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/errors.md Returns the last error in the collection, or `nil` if empty. ```go if lastErr := c.Errors.Last(); lastErr != nil { log.Printf("Last error: %v", lastErr.Err) } ``` -------------------------------- ### With Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/engine.md Returns the Engine with the configuration set in the OptionFunc list. This allows for fluent configuration of the engine. ```APIDOC ## With ### Description Returns the Engine with the configuration set in the OptionFunc list. This allows for fluent configuration of the engine. ### Method `With` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go engine := gin.New().With( func(e *gin.Engine) { e.MaxMultipartMemory = 64 << 20 }, ) ``` ### Response #### Success Response `*Engine` - The configured Engine #### Response Example None ``` -------------------------------- ### HEAD Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/routergroup.md Registers a HEAD route. This method is similar to GET but only retrieves the headers, not the body. ```APIDOC ## HEAD /:relativePath ### Description Registers a HEAD route. This method is similar to GET but only retrieves the headers, not the body. ### Method HEAD ### Endpoint /:relativePath ### Parameters #### Path Parameters - **relativePath** (string) - Required - Path relative to group base - **handlers** (...HandlerFunc) - Required - Handler and optional middleware ### Request Example ```go api.HEAD("/users", headHandler) ``` ### Response #### Success Response (200) - **IRoutes** (IRoutes) - The group for chaining ``` -------------------------------- ### Custom HTTP Server Configuration with Gin Source: https://github.com/gin-gonic/gin/blob/master/docs/doc.md Demonstrates how to use `http.ListenAndServe()` directly with a Gin router for custom HTTP server configurations. ```go func main() { router := gin.Default() http.ListenAndServe(":8080", router) } ``` ```go func main() { router := gin.Default() s := &http.Server{ Addr: ":8080", Handler: router, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } s.ListenAndServe() } ``` -------------------------------- ### Curl Command for Multiple File Upload Source: https://github.com/gin-gonic/gin/blob/master/docs/doc.md Example cURL command to test the multiple file upload endpoint. ```bash curl -X POST http://localhost:8080/upload \ -F "upload[]=@/Users/appleboy/test1.zip" \ -F "upload[]=@/Users/appleboy/test2.zip" \ -H "Content-Type: multipart/form-data" ``` -------------------------------- ### Configure Gin Engine with OptionFunc Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/configuration.md Illustrates using the OptionFunc pattern to configure a Gin engine, either directly with anonymous functions or by using helper functions for cleaner syntax. ```go router := gin.New( func(e *gin.Engine) { e.MaxMultipartMemory = 100 << 20 }, func(e *gin.Engine) { e.HandleMethodNotAllowed = true }, ) // Or with custom helper: func WithMaxMemory(size int64) gin.OptionFunc { return func(e *gin.Engine) { e.MaxMultipartMemory = size } } router := gin.New(WithMaxMemory(100 << 20)) ``` -------------------------------- ### Curl Command for Single File Upload Source: https://github.com/gin-gonic/gin/blob/master/docs/doc.md Example cURL command to test the single file upload endpoint. ```bash curl -X POST http://localhost:8080/upload \ -F "file=@/Users/appleboy/test.zip" \ -H "Content-Type: multipart/form-data" ``` -------------------------------- ### Get JSON Representation of Errors Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/errors.md Returns a JSON-serializable representation of all errors. This can be a single error JSON, an array, or nil. ```go c.Error(errors.New("validation failed")).SetType(gin.ErrorTypePublic) json := c.Errors.JSON() c.JSON(400, gin.H{"errors": json}) ``` -------------------------------- ### Get Cookie Value Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/context.md Retrieves the value of a specific cookie by its name. Handles cases where the cookie might not be present. ```go sessionID, err := c.Cookie("sessionid") if err != nil { // Cookie not found } ``` -------------------------------- ### Sample Output for Custom Log Format Source: https://github.com/gin-gonic/gin/blob/master/docs/doc.md An example of the output generated by the custom log format defined using LoggerWithFormatter. ```sh ::1 - [Fri, 07 Dec 2018 17:04:38 JST] "GET /ping HTTP/1.1 200 122.767µs "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36" " ``` -------------------------------- ### BasePath Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/routergroup.md Returns the base path of the RouterGroup. For example, if a group is created with `router.Group("/rest/n/v1/api")`, this returns `/rest/n/v1/api`. ```APIDOC ## BasePath ### Description Returns the base path of the RouterGroup. For example, if a group is created with `router.Group("/rest/n/v1/api")`, this returns `/rest/n/v1/api`. ### Method `*RouterGroup.BasePath` ### Returns - `string` - The base path of the group ### Example ```go api := router.Group("/api/v1") basePath := api.BasePath() // "/api/v1" ``` ``` -------------------------------- ### Using Middleware in Gin Source: https://github.com/gin-gonic/gin/blob/master/docs/doc.md Demonstrates adding global and per-route middleware, including custom middleware like `MyBenchLogger` and `AuthRequired`. ```go func main() { // Creates a router without any middleware by default r := gin.New() // Global middleware // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release. // By default gin.DefaultWriter = os.Stdout r.Use(gin.Logger()) // Recovery middleware recovers from any panics and writes a 500 if there was one. r.Use(gin.Recovery()) // Per route middleware, you can add as many as you desire. r.GET("/benchmark", MyBenchLogger(), benchEndpoint) // Authorization group // authorized := r.Group("/", AuthRequired()) // exactly the same as: authorized := r.Group("/") // per group middleware! in this case we use the custom created // AuthRequired() middleware just in the "authorized" group. authorized.Use(AuthRequired()) { authorized.POST("/login", loginEndpoint) authorized.POST("/submit", submitEndpoint) authorized.POST("/read", readEndpoint) // nested group testing := authorized.Group("testing") // visit 0.0.0.0:8080/testing/analytics testing.GET("/analytics", analyticsEndpoint) } // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` -------------------------------- ### Register POST Route Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/routergroup.md Registers POST routes within a group, including examples with specific middleware for validation and authentication. ```go api.POST("/users", createUserValidator, createUser) api.POST("/auth/login", login) api.POST("/upload", uploadFile) ``` -------------------------------- ### Create and Use RouterGroup Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/routergroup.md Demonstrates creating a new RouterGroup with a relative path and optional middleware, then adding routes to it. Also shows creating a nested group with its own middleware. ```go router := gin.Default() // Create an API v1 group api := router.Group("/api/v1") // Add routes to the group api.GET("/users", listUsers) api.GET("/users/:id", getUser) api.POST("/users", createUser) // Nested group with middleware protected := api.Group("/protected", authMiddleware) protected.GET("/profile", getProfile) protected.PUT("/profile", updateProfile) ``` -------------------------------- ### Get Last Handler from HandlersChain Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/types.md The Last method returns the final handler in a HandlersChain. It returns nil if the chain is empty. ```Go chain := gin.HandlersChain{middleware1, middleware2, mainHandler} handler := chain.Last() // Returns mainHandler ``` -------------------------------- ### Get RouterGroup BasePath Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/routergroup.md Retrieves the base path of a RouterGroup. This is useful for understanding the prefix applied to routes within that group. ```go api := router.Group("/api/v1") basePath := api.BasePath() // "/api/v1" ``` -------------------------------- ### Serve Files from a Directory Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/routergroup.md Use the Static method to serve all files from a specified directory under a given HTTP path prefix. Files in the directory become accessible via the relativePath. ```Go router.Static("/public", "./public") router.Static("/static", "/var/www/static") api := router.Group("/api") api.Static("/assets", "./assets") ``` -------------------------------- ### Create Default Gin Router Source: https://github.com/gin-gonic/gin/blob/master/docs/doc.md Illustrates creating a Gin router with default Logger and Recovery middleware already attached. ```go // Default With the Logger and Recovery middleware already attached r := gin.Default() ``` -------------------------------- ### Serve File from Filesystem Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/rendering.md Serves a file directly from the filesystem. The Content-Type is automatically detected from the file extension. ```go router.GET("/download/report", func(c *gin.Context) { c.File("/path/to/report.pdf") }) router.GET("/image", func(c *gin.Context) { c.File("./public/image.jpg") }) ``` -------------------------------- ### Configure Engine with Options Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/engine.md The With method allows configuring the Engine using a list of OptionFunc. This is useful for setting parameters like MaxMultipartMemory. ```go engine := gin.New().With( func(e *gin.Engine) { e.MaxMultipartMemory = 64 << 20 }, ) ``` -------------------------------- ### Load HTML Templates in Gin Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/QUICK_START.md Demonstrates different ways to load HTML templates, including from a directory, specific files, or a filesystem. Custom template functions can also be set. ```go router.LoadHTMLGlob("templates/*.html") // Load specific files router.LoadHTMLFiles("templates/index.html", "templates/user.html") // Load from filesystem router.LoadHTMLFS(os.DirFS("templates"), "*.html") // Custom functions router.SetFuncMap(template.FuncMap{ "upper": strings.ToUpper, }) // Use template router.GET("/", func(c *gin.Context) { c.HTML(200, "index.html", gin.H{"title": "Home"}) }) ``` -------------------------------- ### Checking Error Type Flags Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/errors.md Example of using the `IsType` method to check if an error has specific type flags set, such as `ErrorTypeBind`. ```go err := c.Error(errors.New("json parsing failed")) err.SetType(gin.ErrorTypeBind | gin.ErrorTypePublic) if err.IsType(gin.ErrorTypeBind) { log.Println("Binding error detected") } ``` -------------------------------- ### Creating a Public Error with Metadata Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/errors.md Example of instantiating a Gin Error with an underlying error, marking it as public, and attaching specific metadata. ```go err := &gin.Error{ Err: errors.New("validation failed"), Type: gin.ErrorTypePublic, Meta: gin.H{"field": "email", "reason": "invalid format"}, } ``` -------------------------------- ### Use Built-in Middleware Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/QUICK_START.md Demonstrates using Gin's built-in middleware for logging, recovery, and basic authentication, as well as wrapping standard http handlers. ```go // Logger router.Use(gin.Logger()) router.Use(gin.LoggerWithConfig(loggerConfig)) // Recovery (panic recovery) router.Use(gin.Recovery()) // Basic authentication router.Use(gin.BasicAuth(gin.Accounts{ "admin": "password", })) // HTTP wrapping router.GET("/", gin.WrapF(http.HandlerFunc(handler))) router.GET("/", gin.WrapH(http.Handler(handler))) ``` -------------------------------- ### Get Request Header Value Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/context.md Retrieves the value of a request header by its key. Useful for accessing information like User-Agent or Authorization. ```go userAgent := c.GetHeader("User-Agent") authorization := c.GetHeader("Authorization") ``` -------------------------------- ### Get Query Parameter Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/context.md Retrieves the first value of a specified query parameter from the URL. Returns an empty string if the parameter is not present. ```go page := c.Query("page") sort := c.Query("sort") ``` -------------------------------- ### Configure Gin Engine Settings Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/configuration.md Demonstrates setting various configuration options for a Gin engine instance, including trusted proxies, routing behavior, path handling, form memory limits, and template loading. ```go engine := gin.New() // Network configuration engine.TrustedPlatform = gin.PlatformCloudflare engine.SetTrustedProxies([]string{"0.0.0.0/0", "::/0"}) // Routing configuration engine.RedirectTrailingSlash = true engine.RedirectFixedPath = true engine.HandleMethodNotAllowed = true engine.RemoveExtraSlash = false // Path handling engine.UseRawPath = false engine.UseEscapedPath = false engine.UnescapePathValues = true // Form handling engine.MaxMultipartMemory = 64 << 20 // 64 MB // Template configuration engine.SetFuncMap(template.FuncMap{ "upper": strings.ToUpper, }) engine.LoadHTMLGlob("templates/**/*.html") // Middleware engine.Use(gin.Logger()) engine.Use(gin.Recovery()) engine.Use(corsMiddleware) // Start server engine.Run(":8080") ``` -------------------------------- ### Get Handler Name Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/api-reference/context.md Retrieves the fully qualified name of the main handler function for the current request. Useful for logging or debugging. ```go name := c.HandlerName() log.Printf("Handler: %s\n", name) ``` -------------------------------- ### Apply Middleware Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/QUICK_START.md Shows how to apply middleware globally, to specific route groups, or on a per-route basis. ```go // Global middleware (all requests) router.Use(gin.Logger()) router.Use(gin.Recovery()) // Custom middleware router.Use(func(c *gin.Context) { log.Println("Before request") c.Next() // Call next handler log.Println("After request") }) // Group middleware api := router.Group("/api") api.Use(authMiddleware) api.GET("/data", handler) // Route-specific middleware router.POST("/users", validateInput, createUser) ``` -------------------------------- ### Serve Static Files with Custom Filesystem in Gin Source: https://github.com/gin-gonic/gin/blob/master/_autodocs/INDEX.md Use router.StaticFS() to serve files from a custom http.FileSystem implementation. ```go router.StaticFS("/assets", http.Dir("./assets")) ``` -------------------------------- ### Basic Response Rendering (JSON, XML, YAML, TOML, ProtoBuf) Source: https://github.com/gin-gonic/gin/blob/master/docs/doc.md Demonstrates how to render responses in different formats using Gin's built-in methods. ```APIDOC ## Response Rendering > Render responses in various formats including JSON, XML, HTML, and more. ### XML, JSON, YAML, TOML and ProtoBuf rendering ```go func main() { r := gin.Default() // gin.H is a shortcut for map[string]any r.GET("/someJSON", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) }) r.GET("/moreJSON", func(c *gin.Context) { // You can also use a struct var msg struct { Name string `json:"user"` Message string Number int } msg.Name = "Lena" msg.Message = "hey" msg.Number = 123 // Note that msg.Name becomes "user" in the JSON // Will output : {"user": "Lena", "Message": "hey", "Number": 123} c.JSON(http.StatusOK, msg) }) r.GET("/someXML", func(c *gin.Context) { c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) }) r.GET("/someYAML", func(c *gin.Context) { c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) }) r.GET("/someTOML", func(c *gin.Context) { c.TOML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) }) r.GET("/someProtoBuf", func(c *gin.Context) { reps := []int64{int64(1), int64(2)} label := "test" // The specific definition of protobuf is written in the testdata/protoexample file. data := &protoexample.Test{ Label: &label, Reps: reps, } // Note that data becomes binary data in the response // Will output protoexample.Test protobuf serialized data c.ProtoBuf(http.StatusOK, data) }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` ```