溫馨提示×

Swagger API在Debian如何測試

小樊
50
2025-04-13 21:22:53
欄目: 智能運維

在Debian上測試Swagger API,可以按照以下步驟進行:

安裝Swagger

  1. 安裝Swagger命令行工具和依賴
go install github.com/swaggo/swag/cmd/swag@latest
go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/files
  1. 在Go項目中添加Swagger注釋

在你的Go代碼中使用Swagger注釋格式為API接口添加注釋。例如,在main.go文件中:

package main

import (
    "github.com/gin-gonic/gin"
    "myapp/docs" // 引入docs包,以便swag自動生成文檔
    swaggerfiles "github.com/swaggo/files"
    ginswagger "github.com/swaggo/gin-swagger"
    "net/http"
)

// @title Swagger example API
// @version 1.0
// @description 這是一個簡單的 API 文檔示例
// @termsOfService http://swagger.io/terms/
// @contact.name api support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @host localhost:8080
// @basePath /api/v1
func main() {
    r := gin.Default()

    // 設置 Swagger 文檔的路由
    r.GET("/swagger/*any", ginswagger.WrapHandler(swaggerfiles.Handler))

    // 注冊 API 路由
    api := r.Group("/api/v1")
    api.GET("/hello", helloworld)

    // 啟動服務
    r.Run(":8080")
}

// @summary 說你好
// @description 輸出一個問候信息
// @tags hello
// @accept json
// @produce json
// @success 200 {string} string "success"
// @router /hello [get]
func helloworld(c *gin.Context) {
    c.JSON(http.StatusOK, gin.H{"message": "hello, world!"})
}
  1. 生成Swagger文檔

在項目根目錄下運行以下命令生成Swagger文檔:

swag init

這將在docs/目錄下生成docs.goswagger.json文件。

運行應用并測試API

  1. 啟動應用
go run main.go
  1. 訪問Swagger文檔

在瀏覽器中訪問http://localhost:8080/swagger/index.html,即可查看自動生成的Swagger文檔并進行API測試。

通過以上步驟,你可以在Debian上成功安裝并測試Swagger API。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女