Handling Various Request Parameters in Go Fiber Framework
Simple Example
All request parameters in the Fiber framework are obtained through the context object Ctx
.
app.Get("/user/:name?", func(c *fiber.Ctx) error {
// Obtain parameters through the Ctx parameter of the route function and call the appropriate method
// Here, the name parameter is obtained through Params
return c.SendString(c.Params("name"))
})
Obtaining Route Parameters
Obtaining parameters from the URL path
// GET http://example.com/user/fenny
app.Get("/user/:name", func(c *fiber.Ctx) error {
c.Params("name") // "fenny"
// ...
})
// GET http://example.com/user/fenny/123
app.Get("/user/*", func(c *fiber.Ctx) error {
c.Params("*") // "fenny/123"
c.Params("*1") // "fenny/123"
c.Params("*", "default value") // Default value can be set with the second parameter
})
Obtaining Int type route parameters
// GET http://example.com/user/123
app.Get("/user/:id", func(c *fiber.Ctx) error {
id, err := c.ParamsInt("id") // int 123 and no error
// ...
})
Obtaining GET Request Query Parameters
// GET http://example.com/?order=desc&brand=nike
app.Get("/", func(c *fiber.Ctx) error {
c.Query("order") // "desc"
c.Query("brand") // "nike"
// Second parameter can be used to set a default value, which will be returned if the parameter does not exist
c.Query("empty", "nike") // "nike"
// ...
})
Returning all query parameters
// GET http://example.com/?name=alex&want_pizza=false&id=
app.Get("/", func(c *fiber.Ctx) error {
m := c.Queries()
m["name"] // "alex"
m["want_pizza"] // "false"
m["id"] // ""
// ...
})
Binding query parameters to a struct object
// Define a struct to receive parameters
// Use query tag to specify the parameter names to be bound
type Person struct {
Name string `query:"name"`
Pass string `query:"pass"`
Products []string `query:"products"`
}
app.Get("/", func(c *fiber.Ctx) error {
// Define a struct variable to receive parameters
p := new(Person)
// Use QueryParser to bind query parameters to variable p
if err := c.QueryParser(p); err != nil {
return err
}
log.Println(p.Name) // john
log.Println(p.Pass) // doe
log.Println(p.Products) // [shoe, hat]
// ...
})
// Execute the following curl command to test
// curl "http://localhost:3000/?name=john&pass=doe&products=shoe,hat"
Obtaining POST Request Form Parameters
app.Post("/", func(c *fiber.Ctx) error {
// Get the first value from the form field "name":
c.FormValue("name")
// => "john" or "" if it does not exist
// ...
})
Handling Body Parameters
It is mainly used for processing POST/PUT requests and supports JSON, XML, and form parameters.
// Define the struct to receive parameters, and define the parameter field names you want to receive through the json, xml, and form tags
// json, xml, form can be selected as needed; it's not necessary to include all of them
type Person struct {
Name string `json:"name" xml:"name" form:"name"`
Pass string `json:"pass" xml:"pass" form:"pass"`
}
app.Post("/", func(c *fiber.Ctx) error {
// Define the struct variable to receive parameters
p := new(Person)
// Use BodyParser to bind the body parameters to the variable p
if err := c.BodyParser(p); err != nil {
return err
}
log.Println(p.Name) // john
log.Println(p.Pass) // doe
// ...
})
// Examples of various types of requests; for JSON format parameter requests, remember to set Content-Type: application/json
// curl -X POST -H "Content-Type: application/json" --data "{\"name\":\"john\",\"pass\":\"doe\"}" localhost:3000
// curl -X POST -H "Content-Type: application/xml" --data "<login><name>john</name><pass>doe</pass></login>" localhost:3000
// curl -X POST -H "Content-Type: application/x-www-form-urlencoded" --data "name=john&pass=doe" localhost:3000
// curl -X POST -F name=john -F pass=doe http://localhost:3000
// curl -X POST "http://localhost:3000/?name=john&pass=doe"
How to retrieve the original body data is as follows:
// curl -X POST http://localhost:8080 -d user=john
app.Post("/", func(c *fiber.Ctx) error {
// Use BodyRaw to return the raw body data
return c.Send(c.BodyRaw()) // []byte("user=john")
})
Retrieving Request Headers
app.Get("/", func(c *fiber.Ctx) error {
c.Get("Content-Type") // "text/plain"
c.Get("CoNtEnT-TypE") // "text/plain"
c.Get("something", "john") // "john"
// ...
})
Retrieving Client IP
app.Get("/", func(c *fiber.Ctx) error {
c.IP() // "127.0.0.1"
// ...
})
If you are deployed on a server using a proxy or load balancer, you need to retrieve the client's IP through the x-forwarded-for header by setting as follows:
app := fiber.New(fiber.Config{
ProxyHeader: fiber.HeaderXForwardedFor,
})
Reading Cookies
app.Get("/", func(c *fiber.Ctx) error {
// Get cookie by key:
c.Cookies("name") // "john"
c.Cookies("empty", "doe") // "doe"
// ...
})