Golang使用swagger生成api接口文档

Golang使用swagger生成api接口文档

现在大部分应用都是前后端分离的项目,那么,前端和后端交互只有通过api接口文档来实现。swagger可以根据注释来生成api接口文档。

本课程预备知识

  • gin
  • gorm
  • mysql

添加库

go get -u github.com/swaggo/swag/cmd/swag
go get github.com/gin-gonic/gin
go get gorm.io/gorm
go get gorm.io/driver/mysql
go get gorm.io/gorm/logger
go get github.com/swaggo/gin-swagger
go get github.com/swaggo/gin-swagger/swaggerFiles

gin+gorm创建一个crud项目

model.go

package main

import (
	"gorm.io/gorm"
)

//this model represent a database table
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Swagger 是一个用于构建、文档化和使用 RESTful Web 服务的开源工具。Swagger 有很多版本,其中 Swagger2 是其中最常用的一个版本。Swagger2 可以通过注解的方式生成 API 接口文档,这些注解包括 @Api、@ApiOperation、@ApiParam 等。 下面是使用 Swagger2 生成 API 接口文档的步骤: 1. 添加 Swagger2 依赖 在项目的 pom.xml 文件中添加 Swagger2 的依赖: ``` <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> ``` 2. 配置 Swagger2 在 Spring Boot 应用的启动类上添加 @EnableSwagger2 注解开启 Swagger2 支持,并配置 Docket 对象: ``` @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } } ``` 这个配置会扫描所有的 Controller 类,并生成 API 接口文档。 3. 添加 Swagger2 注解 在 Controller 类的方法上添加 Swagger2 注解,包括: - @Api:用于标识这个 Controller 类的作用和说明。 - @ApiOperation:用于标识这个方法的作用和说明。 - @ApiParam:用于标识方法参数的作用和说明。 示例代码: ``` @RestController @RequestMapping("/api") @Api(value = "HelloWorldController", description = "示例控制器") public class HelloWorldController { @GetMapping("/hello") @ApiOperation(value = "打招呼", notes = "向用户打招呼") public String hello(@ApiParam(name = "name", value = "用户名", required = true) @RequestParam String name) { return "Hello, " + name + "!"; } } ``` 4. 访问 Swagger UI 启动应用后,访问 http://localhost:8080/swagger-ui.html 可以看到 Swagger UI 界面,其中包含了生成API 接口文档。在这个界面中,可以查看 API 接口的详细信息、测试 API 接口等。 以上就是使用 Swagger2 生成 API 接口文档的步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

多课网_老郭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值