title | keywords | |||
---|---|---|---|---|
Vercel |
|
This example demonstrates how to deploy a Go Fiber application to Vercel.
This project provides a starting point for deploying a Go Fiber application to Vercel. It includes the necessary configuration files and code to run a serverless application on Vercel.
- Go 1.18 or higher
- Git
- Vercel CLI
api/index.go
: The main entry point for the serverless function.vercel.json
: Configuration file for Vercel.go.mod
: The Go module file.
-
Clone the repository:
git clone https://github.com/gofiber/recipes.git cd recipes/vercel
-
Install the dependencies:
go mod download
Ensure the vercel.json
file is present in the root directory to handle routing properly. This file rewrites all requests to the api/index.go
handler.
{
"rewrites": [
{ "source": "(.*)", "destination": "api/index.go" }
]
}
-
Install the Vercel CLI:
npm install -g vercel
-
Log in to Vercel:
vercel login
-
Deploy the application:
vercel
Follow the prompts to complete the deployment. Your application will be deployed to Vercel and a URL will be provided.
- Open your browser and navigate to the provided Vercel URL.
- You should see the JSON response with the URI and path.
The main Go file sets up the Fiber application, handles HTTP requests, and manages the routing.
package handler
import (
"github.com/gofiber/fiber/v2/middleware/adaptor"
"github.com/gofiber/fiber/v2"
"net/http"
)
// Handler is the main entry point of the application. Think of it like the main() method
func Handler(w http.ResponseWriter, r *http.Request) {
// This is needed to set the proper request path in `*fiber.Ctx`
r.RequestURI = r.URL.String()
handler().ServeHTTP(w, r)
}
// building the fiber application
func handler() http.HandlerFunc {
app := fiber.New()
app.Get("/v1", func(ctx *fiber.Ctx) error {
return ctx.JSON(fiber.Map{
"version": "v1",
})
})
app.Get("/v2", func(ctx *fiber.Ctx) error {
return ctx.JSON(fiber.Map{
"version": "v2",
})
})
app.Get("/", func(ctx *fiber.Ctx) error {
return ctx.JSON(fiber.Map{
"uri": ctx.Request().URI().String(),
"path": ctx.Path(),
})
})
return adaptor.FiberApp(app)
}
This example provides a basic setup for deploying a Go Fiber application to Vercel. It can be extended and customized further to fit the needs of more complex applications.