keyboard_tabSkip to content
listGoAPI Essential

ลง Swagger

สารบัญ

Swagger

Ref: https://github.com/gofiber/swagger

Note

  • Go มี library ของ swagger ที่ใช้งานคู่กับ Fiber ที่ทำให้ออก API documentation format swagger ออกมาได้
  • สำหรับใครที่อยากพัฒนาแล้วมี document ตามไปเลย = สามารถใช้วิธีนี้ได้
bash
go get -u github.com/swaggo/swag/cmd/swag
go get -u github.com/gofiber/swagger

สร้าง swagger document

bash
export PATH=$PATH:$HOME/go/bin
swag init

ที่ main.go

go
package main

import (
  "fmt"
  "time"

  "github.com/gofiber/fiber/v2"
  "github.com/gofiber/jwt/v2"
  "github.com/golang-jwt/jwt/v4"
  "github.com/gofiber/swagger"
  _ "github.com/mikelopster/fiber-basic/docs" // load generated docs
)

// @title Book API
// @description This is a sample server for a book API.
// @version 1.0
// @host localhost:8080
// @BasePath /
// @schemes http
// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name Authorization
func main() {
  // ... code เหมือนเดิม
}

ที่ book.go (ลองเพิ่มสัก 1 function)

go
// Handler functions
// getBooks godoc
// @Summary Get all books
// @Description Get details of all books
// @Tags books
// @Accept  json
// @Produce  json
// @Security ApiKeyAuth
// @Success 200 {array} Book
// @Router /book [get]
func getBooks(c *fiber.Ctx) error {
  // Retrieve user data from the context
  user := c.Locals(userContextKey).(*UserData)

  // Use the user data (e.g., for authorization, custom responses, etc.)
  fmt.Printf("User Email: %s, Role: %s\n", user.Email, user.Role)

  return c.JSON(books)
}

ทุกครั้งที่แก้เสร็จ ให้ run

bash
swag init

อีก 1 ที = จะได้ document ตัวใหม่ออกมา

ลองทดสอบยิงดูจาก swagger

swagger-01

เรื่องอื่นๆ ของ Fiber