GIN-Gonic Flashcards

1
Q

What is the Gin framework

A

“A high-performance HTTP web framework for Go designed for building fast and efficient web apps/APIs”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you install Gin

A

“Run the command: go get -u github.com/gin-gonic/gin”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What does the gin.Default() function do

A

“Creates a Gin router with default middleware (logging and recovery)”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How to define a GET route for the root path in Gin

A

“r.GET(“/”, handlerFunction)”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What method sends a plain text response in Gin

A

“c.String(statusCode, content)”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to start a Gin server on port 8080

A

“r.Run(“:8080”)”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How to extract a path parameter named ““name”” in Gin

A

“Use c.Param(““name””)”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to access a query parameter ““q”” in Gin

A

“Use c.Query(““q””)”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is middleware in Gin

A

“Functions that process requests before reaching the final handler (e.g., logging/auth)”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How to create custom middleware for authentication

A

“Define a function that checks tokens and uses c.AbortWithStatusJSON() or c.Next()”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How to apply middleware to a specific route

A

“Add the middleware as an argument in the route definition: r.GET(“/secure”, AuthMiddleware, handler)”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are route groups used for in Gin

A

“To organize routes with shared prefixes or middleware”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How to serve static files from a “./static” directory

A

“Use r.Static(“/static”, “./static”)”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How to bind JSON data to a struct in Gin

A

“Use c.ShouldBindJSON(&structVariable) inside the handler”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the purpose of binding tags like ““binding:”“required”””

A

“To enforce validation rules for incoming data”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How to handle file uploads in Gin

A

“Use c.FormFile(““file””) and c.SaveUploadedFile()”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How to send a JSON response in Gin

A

“Use c.JSON(statusCode, data)”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How to render HTML templates in Gin

A

“Load templates with r.LoadHTMLGlob() and use c.HTML() in handlers”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What does the Recovery middleware do

A

“Handles panics gracefully and prevents server crashes”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How to create a custom validation rule like ““is_cool”” in Gin

A

“Register it via validator.Validate.RegisterValidation()”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How to test Gin handlers

A

“Use Go’s httptest package to simulate requests and record responses”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What command builds a production binary for a Gin app

A

“go build -o app”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How to run Gin in production mode

A

“Set environment variable: GIN_MODE=release”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Name two best practices for Gin deployment

A

“Use structured logging and implement graceful shutdown”

25
What library can be used for rate limiting in Gin
github.com/ulule/limiter/v3
26
27
What is the purpose of the `Param(key string) string` method in Gin's `Context`?
Extracts path parameters from the URL. For example, in the route `/user/:id`, calling `c.Param(\"id\")` returns the value associated with `id`.
28
How do you retrieve query parameters using Gin's `Context`?
Use the `Query(key string) string` method. For instance, for the URL `/search?q=gin`, `c.Query(\"q\")` returns `\"gin\"`.
29
Which method in Gin's `Context` is used to obtain request headers?
The `GetHeader(key string) string` method retrieves the value of the specified request header.
30
How can you bind a JSON request body to a struct in Gin?
By using the `ShouldBindJSON(obj interface{}) error` method. Example: `err := c.ShouldBindJSON(&user)` binds the JSON body to the `user` struct.
31
What is the function of the `FormFile(name string) (*multipart.FileHeader, error)` method?
It retrieves uploaded files from a form. For example, `file, _ := c.FormFile(\"avatar\")` gets the file associated with the form field named `\"avatar\"`.
32
How do you send a JSON response using Gin's `Context`?
Utilize the `JSON(code int, obj interface{})` method. Example: `c.JSON(200, gin.H{\"status\": \"success\"})` sends a JSON response with a status of `\"success\"`.
33
What method would you use to render HTML templates in Gin?
The `HTML(code int, name string, obj interface{})` method. After loading templates with `r.LoadHTMLGlob(\"templates/*\")`, you can render them using `c.HTML(200, \"index.html\", gin.H{\"title\": \"Home\"})`.
34
How can you send a plain text response in Gin?
"By using the `String(code int, format string, values ...interface{})` method. Example: `c.String(200, \"Hello
35
What is the purpose of the `Redirect(code int, location string)` method in Gin?
It redirects the client to a new URL. For instance, `c.Redirect(301, \"/login\")` redirects the client to the `/login` page with a 301 status code.
36
How do you bind path parameters to a struct in Gin?
Use the `ShouldBindUri(obj interface{}) error` method. Example: `c.ShouldBindUri(&userURI)` binds `/user/:id` to `UserURI.ID`.
37
Which method allows binding of query parameters to a struct in Gin?
The `ShouldBindQuery(obj interface{}) error` method. For example, `c.ShouldBindQuery(&filter)` binds `?page=2` to `Filter.Page`.
38
What does the `Next()` method do in Gin's middleware?
It passes control to the next handler in the middleware chain. Example: `c.Next()` proceeds to the next handler after executing the current middleware logic.
39
When would you use the `Abort()` method in Gin?
To stop the current handler chain, often used in middleware. For instance, if a user is not authenticated, `c.Abort()` can halt further processing.
40
How can you abort the handler chain and send a JSON response immediately in Gin?
By using the `AbortWithStatusJSON(code int, obj interface{})` method. Example: `c.AbortWithStatusJSON(400, gin.H{\"error\": \"Invalid input\"})`.
41
What is the function of the `SaveUploadedFile(file *multipart.FileHeader, dst string) error` method?
It saves an uploaded file to disk. For example, `c.SaveUploadedFile(file, \"uploads/avatar.jpg\")` saves the uploaded file to the specified path.
42
How do you serve a file as the response in Gin?
Use the `File(filepath string)` method. Example: `c.File(\"static/image.png\")` serves the file located at `\"static/image.png\"`.
43
Which method in Gin's `Context` allows you to add an error to the context?
The `Error(err error)` method. Example: `c.Error(errors.New(\"validation failed\"))` adds an error to the context.
44
How can you retrieve all errors attached to the context in Gin?
By accessing the `Errors` field. Example: `errors := c.Errors` retrieves all errors associated with the context.
45
What is the purpose of the `Get(key string) (value interface{}, exists bool)` method in Gin?
It retrieves data stored in the context, often set by middleware. Example: `user, exists := c.Get(\"user\")` gets the `\"user\"` value if it exists.
46
How do you store data in the context for later use in Gin?
Use the `Set(key string, value interface{})` method. Example: `c.Set(\"request_id\", \"123\")` stores the value `\"123\"` with the key `\"request_id\"`.
47
Which method retrieves the client's IP address in Gin?
The `ClientIP() string` method. Example: `ip := c.ClientIP()` gets the client's IP address, accounting for proxies.
48
How can you determine the MIME type of the request in Gin?
By using the `ContentType() string` method. Example: `if c.ContentType() == \"application/json\" { // Handle JSON }` checks if the request is of type `\"application/json\"`.
49
What is `gin.HandlerFunc`?
A function type in Gin that handles HTTP requests: `type HandlerFunc func(*gin.Context)`.
50
Why return `gin.HandlerFunc` instead of defining it directly?
To enable dependency injection (e.g., pass a database) or create reusable/closured handlers.
51
What is a key use case for returning `gin.HandlerFunc`?
Injecting dependencies like a database: `func GetUser(db *DB) gin.HandlerFunc { ... }`.
52
What happens if you don’t return `gin.HandlerFunc`?
You lose flexibility (e.g., can’t inject dependencies) and must define handlers statically.
53
How do you set up a route with a handler that returns `gin.HandlerFunc`?
`router.GET(\"/path\", GetUser())` (note the `()` to invoke the factory function).
54
What is a key takeaway about `gin.HandlerFunc`?
Returning it acts like a factory, creating configured handlers for routes.
55
What HTTP status code should authorization failures use?
`http.StatusForbidden` (403), not `BadRequest` (400).
56
How to set up a route with a direct handler function?
`router.GET(\"/path\", GetUser)` (no `()`, passes function directly).
57
What analogy explains returning `gin.HandlerFunc`?
Think of it as a factory producing handlers with dependencies pre-configured.
58
What’s wrong with `CheckUserType(c, userType)` in `MatchUserTypeToUid`?
It’s redundant; `userType` is already known, so the check always passes.