Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 39 ยท Projects and Practice

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.

Reading about a framework is not the same as using it. This final lesson gives you exercises to build skill, a few runnable puzzles that test your mental model of how Gin works, and the interview questions that come up again and again, each with a short, accurate answer. Try each exercise on your own before opening the solution.

Gin is not available in the in-page runner, so the runnable puzzles reproduce Gin's behaviour with plain Go that you can edit and rerun. The real Gin code is shown read-only.

Puzzle 1: the middleware chain

Gin runs middleware as a chain. Each handler calls c.Next() to run the rest of the chain and then continues with whatever comes after it, so code before Next runs on the way in and code after it runs on the way out. c.Abort() stops the rest of the chain from running. The stand-in below implements exactly that with a small context.

Predict the output before you run it. Then move the Abort to the second middleware and predict again.

Go Predict the middleware order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

You should see that for the allowed request the "after" lines print in reverse order (auth first, then logger) like unwinding a stack, and that for the denied request the handler never runs but logger: after still does. This is why a logging middleware placed first can still record the status of a request that a later middleware rejected. See Middleware in Gin for the real API, and remember to return after c.Abort in your own code: Abort does not stop the current function.

Puzzle 2: pagination arithmetic

Exercise: given page and per_page from the query string, compute the OFFSET, clamp bad values (page below 1 becomes 1; per_page outside 1 to 100 becomes 20) and the total number of pages. Write it first, then compare.

Go Pagination helper: your turn, then compare

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Notice the ceiling division trick (total + perPage - 1) / perPage, and that asking for a page beyond the last one is a decision you must make (return an empty list, or clamp). The Gin and GORM version is in GORM Queries and Pagination.

Exercises

Do these in a real Gin project (go mod init, go get github.com/gin-gonic/gin). Aim for each to take 20 to 60 minutes.

Beginner

  1. A GET /hello/:name route that answers {"message": "Hello, <name>!"} and a ?lang=es option that changes the greeting. Add a test with httptest.
  2. A POST /echo endpoint that binds {"text": "..."}, rejects empty or longer than 100 characters with 400, and returns the text reversed.
  3. A route group /v1 with a GET /time endpoint that returns the server time in UTC as RFC 3339.

Intermediate

  1. Write a middleware that adds an X-Request-ID header (reusing the incoming one if present) and stores it in the context. Use it in your error responses.
  2. Add POST /upload accepting a single image up to 2 MB, only PNG or JPEG (check the real content with http.DetectContentType), saved under a generated name.
  3. Build a GET /products endpoint with ?q=, ?min_price=, ?sort=price filters on a GORM model with a whitelist for the sort column.
  4. Add JWT login and a GET /me route. Write tests for the missing, expired and valid token cases.

Advanced

  1. Implement per-IP rate limiting with golang.org/x/time/rate, expire idle limiters after 10 minutes, and test it with a fake clock.
  2. Serve a server-rendered page with an embedded layout via go:embed, a form with CSRF protection and flash messages.
  3. Make the app shut down gracefully, flush a background click counter, and prove it with a test that starts the server on port 0.

For each exercise, check the checklist: input validated? status codes right? errors consistent? tests written? secrets from the environment? logs free of sensitive data?

Interview questions

What is Gin and why use it instead of net/http? Gin is an HTTP web framework for Go built around a fast radix-tree router. On top of net/http it adds path parameters, route groups, middleware chaining, data binding and validation, and convenient response helpers. It is still just an http.Handler, so you can mix it with the standard library. Since Go 1.22 the standard ServeMux supports methods and wildcards, so the gap is smaller, but Gin's middleware and binding ergonomics remain popular.

What does gin.Default() give you compared with gin.New()? gin.New() is an empty engine. gin.Default() is New() plus the Logger and Recovery middleware.

How do c.Next() and c.Abort() differ? Next runs the remaining handlers in the chain and returns when they finish. Abort prevents the remaining handlers from running; it does not return from your function, so you usually return right after it. AbortWithStatusJSON combines aborting with writing a response.

What is the difference between ShouldBind... and Bind...? Bind methods write a 400 response and abort automatically on error. ShouldBind methods only return the error and leave the response to you, which is preferred when you want a consistent error format.

How does Gin validate input? It uses the go-playground/validator library through binding:"..." struct tags such as required, email, min, max, oneof. You can register custom validators and translate messages.

How do you share data between middleware and handlers? With c.Set(key, value) and c.Get(key) (or typed helpers such as c.GetString) on the request context. Values live only for that request. Pass long-lived dependencies (database, config) through a struct that owns the handlers instead.

Is a Gin *gin.Context safe to use from a goroutine? Not directly. Contexts are pooled and reused after the handler returns. Use c.Copy() to get a safe read-only copy for goroutines.

How do you handle graceful shutdown? Create your own http.Server, listen for SIGINT/SIGTERM with signal.NotifyContext, and call Shutdown with a timeout. See Graceful Shutdown, Logging and Observability.

How would you structure a large Gin application? Keep main thin; put configuration, models, stores (behind interfaces), handlers, middleware and routing into separate packages under internal/, inject dependencies, and build the router in a SetupRouter(deps) function so it is testable. See Project Structure.

How do you prevent SQL injection and XSS? Use parameterized queries (? placeholders in GORM), whitelist sort and filter columns, and render with html/template, which escapes by context. Validate all input and never mark untrusted text as template.HTML.

How do you secure an API? HTTPS at the proxy, password hashing with bcrypt or argon2, short-lived JWTs or server-side sessions, authorization checks scoped by the authenticated user, CORS configured to known origins, security headers, rate limiting, body size limits and server timeouts.

What is a common gotcha with route parameters? Wildcard conflicts and ordering: the same path segment cannot be both a different named parameter in sibling routes (/users/:id and /users/:name), and a catch-all *path must be last.

Where to go next

  • Add the Gin pieces you have not used: gin-contrib/cors, sessions, gzip, and multitemplate.
  • Learn OpenAPI documentation with swaggo/swag and generate a client for your API.
  • Try a second framework (Echo, Fiber, Chi) or the plain net/http router, and compare; the concepts transfer. The Go tutorial fills in the language side.
  • Move on to databases beyond GORM: raw database/sql, sqlc and migrations with golang-migrate.
  • Study production topics: caching with Redis, background jobs, message queues, and tracing with OpenTelemetry.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a chain logger -> auth -> handler where auth calls c.Abort(), which lines print?

    Abort stops later handlers, but the earlier middleware continues after its c.Next() returns.
  2. 2. Which is the safe way to use the context in a goroutine started by a handler?

    The original context is reused for later requests; a copy is detached.
  3. 3. What does Bind do on error that ShouldBind does not?

    ShouldBind leaves the response to you, which allows a consistent error format.
  4. 4. What is the difference between gin.New() and gin.Default()?

    gin.Default() is gin.New() with the Logger and Recovery middleware already attached.
  5. 5. How many pages are needed for 101 items at 20 per page?

    Ceiling of 101 / 20 is 6; the integer expression (101 + 19) / 20 gives 6.

Summary

  • Middleware forms a stack: code before Next runs on the way in, after it on the way out; Abort stops later handlers.
  • Pagination needs clamping and ceiling division; decide how to treat pages past the end.
  • The exercises move from routes and binding to middleware, uploads, GORM filters, JWT, rate limiting, templates and shutdown.
  • Interview answers revolve around the same themes: routing, middleware, binding, safety, structure, testing and deployment.

Back to the track page: Gin Web Framework