在Debian系统下生成Swagger文档,通常需要使用特定的工具和库。以下是基于Go语言和Spring Boot框架的两种常见方法的详细步骤。
安装Swag工具:
打开终端,运行以下命令来安装Swag工具:
go install github.com/swaggo/swag/cmd/swag@latest
初始化Swagger文档:
在你的Go项目目录中,运行以下命令来初始化Swagger文档:
swag init
这将会在你的项目中生成一个docs.go
文件,其中包含了Swagger文档的配置信息。
在代码中添加Swagger注释:
在你的Go代码中,使用特定的注释来描述API的端点、请求参数、响应格式等信息。例如:
// @Summary 获取用户信息
// @Description 获取用户信息
// @Tags Users
// @Accept json
// @Produce json
// @Param id path int true "用户ID"
// @Success 200 {object} User
// @Router /users/{id} [get]
func getUser(c *gin.Context) {
// ...
}
生成Swagger文档:
在添加了必要的注释后,再次运行swag init
命令来生成最新的Swagger文档。
添加Swagger依赖:
在你的pom.xml
文件中添加以下依赖:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
配置Swagger:
创建一个配置类,使用@Configuration
和@EnableSwagger2
注解来启用Swagger:
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
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("cn.weijishu.server.api.rest"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Weijishu Swagger API Document")
.description("Weijishu Swagger Description...")
.contact(new Contact("Weijishu", "https://www.weijisu.cn/", "mail@weijishu.cn"))
.version("0.1")
.build();
}
}
使用Swagger注解:
在你的控制器中使用Swagger注解来标记API:
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import org.springframework.web.bind.annotation.*;
@Api(tags = ["SwaggerDemo"])
@RestController
@RequestMapping("/weijishu")
public class WeijishuSwagger2Controller {
@ApiOperation(value = "方法说明", notes = "通过A")
@ApiBody(description = "请求体描述")
@ApiResponse(status = 200, description = "成功")
@ApiResponse(status = 400, description = "错误")
@PostMapping("/add")
public ResponseEntity<String> add(@RequestBody String requestBody) {
// ...
return ResponseEntity.ok("Success");
}
}
访问Swagger文档:
启动你的Spring Boot应用后,可以通过访问http://localhost:端口号/swagger-ui.html
来查看和测试Swagger文档。
请注意,具体的步骤可能会根据你使用的框架和库有所不同。建议参考官方文档以获取最准确的信息。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:Debian下Swagger文档如何生成