Embedding Nuxt Frontend into Go App
We will create a Go application with web interface powered by the Nuxt and served with Fiber framework.
Prepare Go project
Read more how to create your First App with Go.
Create component for Web Interface
Make directory ./frontend
to store our web interface and component to embed static files:
mkdir -p frontend
Create Nuxt Project
In console, open the ui component directory and create new Nuxt project:
cd frontend
npx nuxi@latest init web
cd web
Read more in the Getting Started guide on official website. In the Nuxt configuration file turn off Server Side Rendering (SSR). Open nuxt.config.ts
file and append ssr
option:
export default defineNuxtConfig({
ssr: false,
})
Now we can build web interface:
npm install
npm run generate
All static files will be stored in the ./frontend/web/.output/public
directory.
Frontend component
Create source file ./frontend/frontend.go
:
package frontend
import (
"embed"
)
//go:embed web/.output/public/*
var FS embed.FS
Server component
Now we can create component to start our HTTP server and serve static files.
Modify file internal/app/app.go
:
package app
import (
"net/http"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/filesystem"
"example/frontend"
)
func Start() error {
server := fiber.New()
// Serve static files
server.Use("/", filesystem.New(filesystem.Config{
Root: http.FS(frontend.FS),
PathPrefix: "web/.output/public",
}))
// For all other routes serve the "index.html"
server.Use("*", func(c *fiber.Ctx) error {
return filesystem.SendFile(c, http.FS(frontend.FS), "web/.output/public/index.html")
})
return server.Listen(":3000")
}
Start project
The cmd source the same as for First App with Go, so just run it:
go run ./cmd/example
and open in your browser http://localhost:3000
Check out this project in our repository.