Optional Parameter Example
This project demonstrates how to handle optional parameters in a Go application using the Fiber framework.
Prerequisites
Ensure you have the following installed:
- Golang
- Fiber package
Setup
-
Clone the repository:
git clone https://github.com/gofiber/recipes.gitcd recipes/optional-parameter -
Install dependencies:
go get
Running the Application
- Start the application:
go run main.go
Example
Here is an example of how to handle optional parameters in a Fiber application:
package main
import (
"log"
"strconv"
"github.com/gofiber/fiber/v3"
)
func main() {
// user list
users := [...]string{"Alice", "Bob", "Charlie", "David"}
// Fiber instance
app := fiber.New()
// Route to profile
app.Get("/:id?", func(c fiber.Ctx) error {
id, err := strconv.Atoi(c.Params("id")) // transform id to array index
if err != nil || id < 0 || id >= len(users) {
return c.SendStatus(fiber.StatusNotFound) // invalid parameter returns 404
}
return c.SendString("Hello, " + users[id] + "!") // custom hello message to user with the id
})
// Start server
log.Fatal(app.Listen(":3000"))
}
In this example:
- The
:id?parameter in the route is optional. - If no valid
idis provided, a404 Not Foundis returned. - Valid
idvalues (0-3) map to users Alice, Bob, Charlie, and David.