In Go-Gin, you can use the c.PostForm method to retrieve form variables from a POST request. The method takes the key of the form variable as its argument and returns the value of the variable as a string.

Here’s an example of how you can use the c.PostForm method to retrieve the value of a form variable named “name”:

1
2
3
4
5
6
7
8
9
10
11
12
package main

import "github.com/gin-gonic/gin"

func main() {
r := gin.Default()
r.POST("/submit", func(c *gin.Context) {
name := c.PostForm("name")
c.String(200, "Hello %s", name)
})
r.Run()
}

In this example, when a user submits a form with a field named “name”, the value of that field will be passed as an argument to the c.PostForm method, which will then assign the value to the variable “name”.

You can also use c.ShouldBind for more complex form structure, and the struct should have the binding:”required” tag on the field you want to be required.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import "github.com/gin-gonic/gin"

type Form struct {
Name string `form:"name" binding:"required"`
Age int `form:"age"`
}

func main() {
r := gin.Default()
r.POST("/submit", func(c *gin.Context) {
var form Form
if err := c.ShouldBind(&form); err != nil {
c.String(http.StatusBadRequest, "bad request: %v", err)
return
}
c.String(200, "Hello %s", form.Name)
})
r.Run()
}

In this example, the struct Form is being used to bind the form data to the struct fields, and the struct field ‘Name’ is marked as required, so if the form data doesn’t contain the ‘Name’ field, it will return a bad request error.