溫馨提示×

Linux Swagger API文檔如何生成

小樊
36
2025-04-21 05:20:23
欄目: 智能運維

在Linux環境下生成Swagger API文檔,通常涉及以下幾個步驟:

使用go swag生成Swagger文檔

  1. 安裝go swag工具

    在終端中運行以下命令來安裝go swag工具:

    go get -u github.com/swaggo/swag/cmd/swag
    
  2. 編寫API注釋

    在您的Go代碼中,使用go swag注釋來描述API接口。例如:

    // @Summary 創建管理員
    // @Description 創建管理員
    // @Tags api.admin
    // @Accept application/x-www-form-urlencoded
    // @Produce json
    // @Param username formdata string true "用戶名"
    // @Param mobile formdata string true "手機號"
    // @Success 200 {object} createresponse
    // @Failure 400 {object} code.failure
    // @Router /api/admin [post]
    
  3. 生成Swagger文檔

    在代碼所在目錄下運行以下命令來生成Swagger文檔:

    swag init
    

    這將在項目目錄下生成一個docs文件夾,其中包含生成的Swagger文檔。

  4. 訪問Swagger UI

    啟動您的應用程序后,可以通過以下URL訪問Swagger UI:

    http://localhost:9999/swagger/index.html
    

    如果您的應用程序配置了安全參數,可能需要根據配置調整訪問權限。

使用Springfox生成Swagger文檔

如果您使用的是Spring Boot項目,可以通過添加Springfox依賴來自動生成Swagger文檔。

  1. 添加Springfox依賴

    pom.xml文件中添加以下依賴:

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>
    
  2. 配置Swagger

    創建一個Swagger配置類,例如:

    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {
        @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example.yourpackage"))
                    .paths(PathSelectors.any())
                    .build();
        }
    }
    
  3. 訪問Swagger UI

    啟動Spring Boot應用程序后,可以通過以下URL訪問Swagger UI:

    http://localhost:8080/swagger-ui.html
    

通過上述步驟,您可以在Linux環境下使用Swagger自動生成API文檔,從而提高開發效率和文檔質量。

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