Chuyển đến nội dung

Bài 39 · Projects and Practice

Gin Practice Exercises

Practice the Gin framework with beginner to advanced exercises, a runnable middleware order puzzle, a pagination challenge and ideas for what to learn next.

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 a quiz. Try each exercise on your own first.

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

When you can solve the exercises, test how well you can explain your choices. The Gin interview questions lesson has 25 questions with answers on routing, middleware, binding, security and testing.

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.
  • Next, practice explaining these ideas with the Gin interview questions.

Next: Gin Interview Questions

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.