Well, let's start to learn more about using a redirect middleware with Fiber. Today, I am a commuter in this project and talking with members about new features, fixes, etc. Let's see the following steps below:
1 - Introduction Fiber
2 - About redirect middleware
3 - Show me the code
4 - Conclusion
1) So, is a framework to implement an API Rest using Golang. It was based on ExpressJS on its type of using, but if we use FastHttp, we can gain much more performance of memory. The smallest problem is that we don't compatible frameworks yet with http/2.0 but the [FastHttp](https://godoc.org/github.com/valyala/fasthttp it's being already implemented and coming soon, so we can use it.
2) Redirect middleware was implemented to create rules to routes definition according to the business rule of the application. You can see documentation about middleware at directly fiber.wiki
3) Let's work!
To start our code we need to install two modules the gofiber/fiber
and gofiber/redirect
. One detail very important is: don't forget to init your module go mod init <your-module>
$ go get -u github.com/gofiber/fiber
$ go get -u github.com/gofiber/redirect
Now, we can implement the first code for this we go to create a file main.go. Later, we must start your package name main and create your function main.
In this snippet of code, we create an API without routes and instance the redirect middleware without rules.
package main
import (
"github.com/gofiber/fiber"
"github.com/gofiber/redirect"
)
func main() {
app := fiber.New()
app.Use(redirect.New())
app.Listen(3000)
}
Let's define our business rules:
we can presume that the API has to have routes to old and new and, then we wish that the old routes could do a redirect for new routes. Show me the code...
func main() {
// ...
app.Use(redirect.New(redirect.Config{
Rules: map[string]string{
"/old": "/new",
"/old/*": "/new/$1",
"/wow": "https://fiber.wiki",
},
StatusCode: 301,
}))
// ...
}
According to the last snippet , we can understand that you also can use redirect to external routes. Now, let's go to create 2 new routes:
// ...
app.Get("/new", func(c *fiber.Ctx) {
c.Send("Hello, World!")
})
app.Get("/new/*", func(c *fiber.Ctx) {
c.Send("Wildcard: ", c.Params("*"))
})
// ...
As soon as you have done, we can go start, run and test our API
$ go run main.go
Later open a new terminal we can running the tests using cURL.
$ curl -svk http://localhost:3000/old
$ curl -svk http://localhost:3000/old/hello
$ curl -svk http://localhost:3000/wow
4) But don't forget, we realized with this tutorial that this framework is very easy to use and we can create powerful rules to redirect from your API.
Top comments (0)