Start with GO lang fiber

記錄一下

fiber v2 + swagger

Environment for Fiber & Swagger

go mod init salary
go get -u github.com/gofiber/fiber/v2
go get -u github.com/gofiber/swagger
go get -u github.com/swaggo/http-swagger
go get -u github.com/gofiber/template/html/v2

swag init

main.go

package main

import (
    "fmt"
    "log"
    "path/filepath"

    "github.com/gofiber/swagger"

    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/cors"
    "github.com/gofiber/fiber/v2/middleware/recover"
    "github.com/gofiber/template/html/v2"

    _ "PROJECT_PATH/docs"
)

// @title Fiber Example API
// @version 1.0
// @description This is a sample swagger for Fiber
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.email fiber@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:8080
// @BasePath /
func main() {
    engine := html.New("./views", ".html")
    app := fiber.New(fiber.Config{
        Views: engine,
    })

    // Middleware
    app.Use(recover.New())
    app.Use(cors.New())

    // Routes
    app.Static("/docs/", "docs")
    app.Static("/html/", "html")
    app.Get("/healthcheck", HealthCheck)

    app.Get("/swagger/*", swagger.HandlerDefault)

    name := "Go Developers"
    fmt.Println("Azure for", name)

    // Start Server
    if err := app.Listen(":8000"); err != nil {
        log.Fatal(err)
    }
}

// HealthCheck godoc
// @Summary Show the status of server.
// @Description get the status of server.
// @Tags root
// @Accept */*
// @Produce json
// @Success 200 {object} map[string]interface{}
// @Router /healthcheck [get]
func HealthCheck(c *fiber.Ctx) error {
    res := map[string]interface{}{
        "data": "server is up",
    }
    if err := c.JSON(res); err != nil {
        return err
    }

    return nil
}