The Fiber framework for the Go programming language offers an extremely efficient and simple way to build web applications and APIs. One of its core features is the ability to serve static HTML pages, making it an excellent choice for web projects that require high speed and low overhead. In this article, we will explore how to configure a Fiber project to serve static HTML pages, moving from creating a new project to configuring the server to serve static files.
First of all, make sure you have Go installed on your machine. Next, you can install Fiber using the go get
:
go get github.com/gofiber/fiber/v2
Once Fiber is installed, you can start by creating a new Go file (for example main.go
) and import the Fiber package:
package main
import (
"github.com/gofiber/fiber/v2"
)
Next, initialize a new Fiber app in your main.go
:
package main
import (
"github.com/gofiber/fiber/v2"
)
func main() {
app := fiber.New()
// Your code will go here
app.Listen(":3000")
}
To serve static HTML pages, Fiber offers a very simple way to do this using the Static
middleware. This middleware allows you to serve static files from a specified directory. For example, if you have a directory called public
containing HTML, CSS, and JavaScript files, you can configure your Fiber server to serve these files with a single line of code:
package main
import (
"github.com/gofiber/fiber/v2"
)
func main() {
app := fiber.New()
// Serve the files in the `public` directory
app.Static("/", "./public")
app.Listen(":3000")
}
With this setup, if there is a file called index.html
in your public
directory, it will be accessible by navigating to http://localhost:3000 /
. All other static files in the public
directory will be accessible via their relative path. For example, if you have a styles.css
file in the public/css
directory, it will be accessible at http://localhost:3000/css/styles.css
.
Conclusions
Serving static HTML pages with Fiber is incredibly simple, making this framework an excellent choice for projects that need a lightweight and fast web server. The combination of the speed of Go and the simplicity of Fiber provides a great platform for developing web applications.
For further customizations and advanced options, I encourage you to consult the official Fiber documentation. However, this introductory guide should give you a solid foundation to start serving static content with Fiber effectively and efficiently.