Gin Web Framework Tutorial
Learn Gin Web Framework step by step: 39 lessons in 9 chapters with examples, quizzes, diagrams and projects.
Start learning →
of lessons completed
Getting Started
- What Is Gin? Learn what the Gin web framework is, how it builds on Go's net/http, why it is fast, what it adds (routing, binding, middleware, rendering) and when to choose it for APIs.
- Your First Gin App Install Gin with go get, write a hello-world server, understand gin.Default versus gin.New, gin.H, the Context and r.Run, and see how the same flow works with a runnable stand-in.
- Gin Modes, Configuration and Environment Understand Gin's debug, release and test modes, GIN_MODE, PORT and trusted proxies, how to load configuration from environment variables, and how to log to a file.
- Structuring a Gin Project Organize a Gin application with cmd and internal folders, handler structs, services and repositories, dependency injection through interfaces, and a routes function you can test.
Routing and Handlers
- Routes and HTTP Methods in Gin Register Gin routes for GET, POST, PUT, PATCH and DELETE, learn what each method means, use Any, Match and Handle, return the right status codes and build a small CRUD API.
- Path and Query Parameters in Gin Read values from the URL in Gin with c.Param, wildcards, c.Query, DefaultQuery, query arrays and maps, and form fields; convert and validate them safely with runnable examples.
- Route Groups in Gin Use r.Group in Gin to share a path prefix and middleware, nest groups, version an API, protect admin routes and build a runnable group stand-in that shows how prefixes and middleware combine.
- Responses in Gin: JSON, XML, Text, Files and Headers Send responses from Gin handlers with c.JSON, IndentedJSON, PureJSON, XML, YAML, String, Data, File and Status; set headers and cookies, shape JSON with struct tags and negotiate content.
- Redirects and Custom 404 Pages in Gin Send redirects with c.Redirect, rewrite routes internally, handle unknown URLs with NoRoute and wrong methods with NoMethod, and try runnable net/http stand-ins for each behavior.
- HTTP Status Codes and Error Responses in Gin Pick the right HTTP status code in Gin handlers, return one consistent JSON error shape, abort safely with AbortWithStatusJSON, and map Go errors to responses with runnable stand-ins.
Binding and Validation
- Binding JSON and Forms in Gin Turn request bodies into Go structs with ShouldBindJSON and ShouldBind, learn the json and form struct tags, the difference between Bind and ShouldBind, and test decoding with runnable stand-ins.
- Binding Query, URI and Headers in Gin Bind query strings, path parameters and HTTP headers into Go structs with ShouldBindQuery, ShouldBindUri and ShouldBindHeader, set defaults, and build a runnable reflection-based binder stand-in.
- Validation Rules in Gin Validate request data in Gin with the binding struct tag and rules required, min, max, len, email, oneof, gte, nested structs, slices and dive. Includes a runnable tag-validator stand-in written in plain Go.
- Custom Validators and Friendly Error Messages in Gin Register custom validation rules in Gin, read validator.ValidationErrors, turn them into field-level JSON messages, validate by hand with struct-level checks, and try a runnable registry stand-in.
Middleware
- Middleware Basics in Gin Understand how Gin middleware works, from the handler chain, c.Next and c.Abort, global versus group versus route middleware, execution order and a runnable chain stand-in that mirrors Gin's context.
- Logger and Recovery Middleware in Gin Learn what gin.Logger and gin.Recovery do, customize the log format and output, skip noisy paths, handle panics with a JSON 500, and build runnable logger and recovery stand-ins with net/http.
- Writing Custom Middleware in Gin Write your own Gin middleware using the closure pattern, request IDs, API-key authentication, passing values with c.Set, middleware with options, testing it, and runnable net/http stand-ins for each idea.
- Middleware for Errors and Timeouts in Gin Centralize error responses with c.Error and an error middleware, limit request time with context deadlines, cap body sizes, and compress responses. Includes runnable net/http stand-ins for each pattern.
Templates and Static Files
- HTML Templates in Gin Render server-side HTML pages in Gin: load templates, pass data with gin.H, use actions, loops and conditions, template functions and automatic escaping.
- Layouts, Partials and Template Inheritance in Gin Share one page layout across many Gin pages with define, template and block, reuse partials, and avoid the name clash that LoadHTMLGlob causes. Runnable stand-ins.
- Static Files and Embedding Assets in Gin Serve CSS, images and JavaScript from Gin with r.Static, StaticFS, StaticFile and c.File, add cache headers, and ship everything in one binary with go:embed.
- File Uploads and Downloads in Gin Accept single and multiple file uploads in Gin with c.FormFile and c.MultipartForm, limit sizes, validate file types, store safely and send downloads with FileAttachment.
Databases and GORM
- GORM Setup and Models for Gin Connect a Gin app to a database with GORM, define models with struct tags, run AutoMigrate, share the connection through dependency injection, and learn what GORM does underneath.
- CRUD with GORM and Gin Build a complete REST CRUD API in Gin with GORM: create, list, get, update (PUT and PATCH) and delete, correct status codes, error mapping and a runnable stand-in.
- Queries, Filtering and Pagination with GORM Build list endpoints in Gin with GORM: Where conditions, safe sorting, offset and keyset pagination, reusable scopes, counting and the SQL injection traps to avoid.
- Relationships and Preloading in GORM Model has-one, has-many, belongs-to and many-to-many relations in GORM, load them with Preload and Joins, avoid the N+1 query problem and return nested JSON from Gin.
- Transactions, Hooks and Migrations in GORM Keep data consistent with GORM transactions, use hooks like BeforeCreate, handle errors and rollback in Gin handlers, and manage schema changes with versioned migrations.
Authentication and Security
- Password Hashing and Cookie Sessions in Gin Store passwords safely with bcrypt, build register and login routes in Gin, keep users signed in with secure session cookies, and protect routes with an auth middleware.
- JWT Authentication in Gin Protect a Gin API with JSON Web Tokens: how a JWT is built and verified, issuing access and refresh tokens, a Bearer auth middleware, roles, and the mistakes that break security.
- CORS, CSRF and Security Headers in Gin Configure CORS correctly in Gin, understand preflight requests, defend against CSRF with SameSite cookies and tokens, and add security headers like CSP and HSTS.
- Rate Limiting and Input Safety in Gin Protect a Gin API from abuse: a token-bucket rate limiter middleware, request body size limits, timeouts, safe validation and the rules that keep untrusted input harmless.
Testing and Deployment
- Testing Gin Handlers Test Gin routes without starting a server: build the router in a function, call ServeHTTP with httptest, assert status and JSON, table-driven tests, auth headers.
- Testing with Databases, Fakes and Middleware Test Gin handlers that use a database: a Store interface with fakes, error injection, in-memory SQLite with GORM, test helpers, middleware tests and integration tests.
- Docker and Deploying a Gin App Ship a Gin service: release mode, twelve-factor configuration from environment variables, a multi-stage Dockerfile, Compose with a database, health checks and a reverse proxy.
- Graceful Shutdown, Logging and Observability Keep a Gin service healthy in production: shut down without dropping requests, structured logs with request IDs using slog, panic recovery, metrics and tracing basics.
Projects and Practice
- Project: A To-Do REST API Build a complete to-do REST API with Gin and GORM: layout, models, validation, CRUD, filtering and pagination, token auth, tests and a runnable stand-in.
- Project: A URL Shortener Build a URL shortener in Gin: short codes with base62, safe URL validation, 301 vs 302 redirects, click counting, caching, a unique-code race and a runnable stand-in.
- Project: A Blog with Server-Rendered Pages Build a blog with Gin and html/template: layouts, post list and detail pages, a create form with validation and flash messages, CSRF protection and a runnable stand-in.
- Gin Practice: Exercises and Interview Questions Practice Gin with hands-on exercises and solutions, a middleware order puzzle, a pagination exercise, common interview questions with short answers, and next steps.