Skip to content

Lesson 40 ยท Projects and Practice

Gin Interview Questions

25 Gin interview questions with short answers for Go developers: routing, middleware, c.Next and c.Abort, binding, validation, security and testing.

Gin interview questions usually test whether you understand how a request moves through the framework, not whether you remember every method name. This page has 25 common questions with short answers, grouped by topic.

Cover each answer, say yours out loud, and then compare. To practice with code, work through the Gin practice exercises.

Basics and routing

1. What is Gin?

Gin is a web framework for Go. It adds a fast router, route groups, middleware, data binding, validation and response helpers on top of net/http. A Gin engine is an http.Handler, so it works with the standard http.Server. See What Is Gin?.

2. When would you choose Gin over plain net/http?

Choose Gin when you want binding, validation, route groups and a ready-made middleware ecosystem. Since Go 1.22, the standard ServeMux matches HTTP methods and path wildcards, so a small service may not need a framework. A good answer names this trade-off: convenience against an extra dependency.

3. Why is Gin's router fast?

It stores routes in a radix tree, an approach that comes from httprouter. Matching follows the characters of the path through the tree instead of testing each route in turn. In most real applications, though, the database and network cost far more than routing.

4. What is the difference between gin.New() and gin.Default()?

gin.New() creates an engine with no middleware. gin.Default() also attaches the Logger and Recovery middleware.

5. How do path parameters, wildcards and query parameters differ?

:id matches one path segment, and *path matches the rest of the path, including slashes. You read both with c.Param. Query parameters come after ?, and you read them with c.Query or c.DefaultQuery. See Path and Query Parameters.

6. What are route groups for?

A group gives several routes a shared prefix and shared middleware. Typical uses are API versions such as /v1 and a protected area that requires authentication:

Go
api := router.Group("/api/v1")
api.Use(RequireAuth())
api.GET("/orders", listOrders)

Middleware and the context

7. How does middleware work in Gin?

A middleware is a gin.HandlerFunc in the same chain as your handler. Code before c.Next() runs on the way in. Code after it runs when the later handlers have finished.

8. What is the difference between c.Next() and c.Abort()?

c.Next() runs the remaining handlers. c.Abort() stops handlers that haven't started yet. It doesn't leave the current function, so you normally return right after it. Middleware that ran earlier still continues after its own c.Next().

9. In what order does middleware run?

In the order you register it: global middleware first, then group middleware, then middleware attached to the route. The code after c.Next() runs in reverse order. Use only affects routes registered after the call.

10. What is gin.Context?

It represents one request and its response. You use it to read input, write output, control the middleware chain and pass values along with c.Set and c.Get.

11. Can you use gin.Context in a goroutine?

Don't pass the original context to a goroutine that may outlive the handler. Gin reuses context objects for later requests. Call c.Copy() first and give the goroutine the copy. Don't write the response from the goroutine.

12. How do you stop slow work when the client disconnects?

Pass c.Request.Context() to your database queries and outgoing requests. It is cancelled when the client's connection closes. Add context.WithTimeout when an operation needs its own limit. Work that must continue after the response needs a separate context and, usually, a job queue.

13. What happens when a handler panics?

With the Recovery middleware, Gin recovers the panic, logs it and responds with status 500. Recovery doesn't cover goroutines that you start yourself. An unrecovered panic in one of them ends the whole program.

Binding and validation

14. What is the difference between Bind and ShouldBind?

On error, the Bind methods abort the request with status 400. The ShouldBind methods only return the error, so you decide what to send. Most APIs use ShouldBind to keep one error format. See Binding JSON and Forms.

15. How do you validate input?

Add binding tags to struct fields. Gin uses the go-playground/validator library, and you can register your own rules.

Go
type SignUp struct {
	Email string `json:"email" binding:"required,email"`
	Age   int    `json:"age" binding:"gte=18,lte=120"`
}

16. Why can required reject a valid 0 or false?

required treats a type's zero value as missing. If 0 or false is a real answer, use a pointer such as *bool. Then nil means the client sent nothing.

17. Why is the request body empty the second time you read it?

The body is a stream, so reading it consumes it. If two bindings must read the same body, ShouldBindBodyWith keeps a copy in the context. It uses extra memory, so use it only when you need it.

Security and production

18. How do you handle file uploads safely?

Limit the body size with http.MaxBytesReader, check the file's content and not only its name, and save it under a name that you generate. MaxMultipartMemory is not an upload limit: it controls how much is kept in memory before the rest goes to temporary files. See File Uploads and Downloads.

19. Why do trusted proxies matter?

c.ClientIP() can read forwarding headers such as X-Forwarded-For, which any client can fake. Call SetTrustedProxies with the addresses of your real proxies, or with nil if you have none. This matters for rate limiting and logs.

20. How do you prevent SQL injection?

Pass values through placeholders (?) instead of building SQL strings. Placeholders can't stand for column names or sort directions, so check those against a list of allowed values.

21. What is release mode?

It turns off Gin's debug output. Set it with the GIN_MODE=release environment variable or gin.SetMode(gin.ReleaseMode). See Modes and Configuration.

22. How do you shut down a Gin server gracefully?

Run the engine inside your own http.Server. Wait for an interrupt or termination signal, for example with signal.NotifyContext, and then call Shutdown with a timeout. The server stops accepting connections and waits for active requests. See Graceful Shutdown and Observability.

Testing and design

23. How do you test a handler without starting a server?

Build the router, create a request with httptest.NewRequest, record the response with httptest.NewRecorder, and call router.ServeHTTP. Then check the status code, headers and body. See Testing Gin Handlers.

24. How do you give handlers a database connection?

Put dependencies in a struct and make the handlers its methods. Depend on small interfaces so that tests can pass in fakes. This is easier to follow and test than global variables.

25. How would you structure a large Gin application?

Keep main small. Separate configuration, handlers, business logic and data access into packages, and build the router in one function that receives its dependencies. There is no single required layout, so explain why you chose yours. See Project Structure.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. You call router.Use(Audit()) after registering GET /health. What happens to /health?

    Use affects only the routes registered after the call.
  2. 2. A JSON field active may be false, but the client must send it. Which field type fits best with binding:"required"?

    With a pointer, nil means missing, while a pointer to false is a value that was sent.
  3. 3. What does MaxMultipartMemory control?

    The rest is written to temporary files. Use http.MaxBytesReader to limit the request size.
  4. 4. Where should a goroutine started by a handler get request data from?

    Gin reuses the original context after the request ends.

Summary

  • Explain the request's path: router, middleware chain, handler, then the code after c.Next().
  • Know the binding differences, especially ShouldBind and zero values with required.
  • For production questions, mention body limits, trusted proxies, release mode and graceful shutdown.
  • Give the trade-off, not only the definition.

Back to the track page: Gin Web Framework

Track your progress

Create a free account to tick off lessons and pick up where you left off on any device.