http fiber ger in go

To get started with fiber in Go, first you need to install the fiber package using the command go get -u github.com/gofiber/fiber/v2. After that, you can create a basic fiber server to serve HTTP requests.

main.go
package main

import (
	"github.com/gofiber/fiber/v2"
)

func main() {
    // Create a new Fiber instance
	app := fiber.New()

    // Define a route handler
	app.Get("/", func(c *fiber.Ctx) error {
		return c.SendString("Hello, World!")
	})

    // Start the server
    err := app.Listen(":3000")
    if err != nil {
        panic(err)
    }
}
344 chars
22 lines

You can run this server by running go run main.go and then accessing http://localhost:3000 in your web browser.

Fiber also supports middleware which can be used to perform actions before or after route handlers are executed. Here's an example of a middleware that logs the time taken to handle each request:

main.go
func LoggerMiddleware(c *fiber.Ctx) error {
	start := time.Now()

	err := c.Next()

	elapsed := time.Since(start).Seconds()

	fmt.Printf("%.3f - %s %s\n", elapsed, c.Method(), c.Path())

	return err
}

// ...

app.Use(LoggerMiddleware)
236 chars
16 lines

This middleware can be added using app.Use and will be run for every request that goes through the server.

gistlibby LogSnag