

Golang,NodeJS(express和nestjs)自动生成swagger
source link: https://studygolang.com/articles/18734?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Golang 自动生成swagger
-
安装
go get -u github.com/swaggo/swag/cmd/swag
-
在项目下执行
swag init
,会生成docs目录。如果目录存在则会报错。 - docs目录下会生成docs.go,swagger.json和swagger.yaml,根据需求使用。
Gin 集成例
- main.go
// @title Sample Service API // @version 1.0 // @description Platform API for Sample. // @contact.name getsu // @contact.url http://www.swagger.io/support // @contact.email [email protected] // @license.name Apache 2.0 // @license.url http://www.apache.org/licenses/LICENSE-2.0.html // @host sample.com // @BasePath /api // @securityDefinitions.apikey ApiKeyAuth // @in header // @name Authorization func setupRouter() *gin.Engine { r := gin.Default() r.Run() }
- Controller.go
//CreateApp create app // CreateApp godoc // @Summary create app // @Description create app // @Accept json // @Produce json // @Param app body dao.App true "create app" // @Success 200 {object} App // @Failure 400 {object} Response // @Failure 500 {object} Response // @Router /app [post] // @Security ApiKeyAuth func CreateApp(c *gin.Context) { //略 }
NodeJS 自动生成swagger
Express框架集成
- 安装
npm i express-swagger-generator --save-dev
- 代码例:
- main.js
var express = require('express'); var bodyParser = require('body-parser'); var controller = require('./controller'); const config = require('./config/config'); var app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); const expressSwagger = require('express-swagger-generator')(app); let options = { swaggerDefinition: { info: { description: 'This is a sample server', title: 'Swagger', version: '1.0.0', }, host: 'localhost:3000', basePath: '/v1', produces: [ "application/json", "application/xml" ], schemes: ['http', 'https'], securityDefinitions: { JWT: { type: 'apiKey', in: 'header', name: 'Authorization', description: "", } } }, route: { url:'/swagger', docs:'/swagger.json', //swagger文件 api }, basedir: __dirname, //app absolute path files: ['./controller/*.js'] //Path to the API handle folder }; expressSwagger(options) app.listen(config.port);
- controller/api.js
/** * api for get request * @route GET /api/run * @returns {object} 200 - An array of user info * @returns {Error} default - Unexpected error */ exports.doGet = function(req, res) { res.setHeader('Content-Type', 'application/json;charset=utf-8'); res.send({ result: true, message: 'ok' }); }; /** * api for post request * @route POST /api/run * @returns {object} 200 - An array of user info * @returns {Error} default - Unexpected error */ exports.doPost = function(req, res) { res.setHeader('Content-Type', 'application/json;charset=utf-8'); res.send({ result: true, message: 'ok' }); };
NestJS 集成
- 安装
npm i --save @nestjs/swagger
During the examination of the defined controllers, the SwaggerModule is looking for all used @Body(), @Query(), and @Param() decorators in the route handlers.
import { NestFactory } from '@nestjs/core'; import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; import { ApplicationModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(ApplicationModule); const options = new DocumentBuilder() .setTitle('Cats example') .setDescription('The cats API description') .setVersion('1.0') .addTag('cats') .build(); const document = SwaggerModule.createDocument(app, options); SwaggerModule.setup('api', app, document); await app.listen(3001); } bootstrap();
Recommend
-
9
参考文档:docs.nestjs.cn 说起Nestjs的异常过滤器,不能不提.Net的全局过滤器Filter,功能那是相当的强悍,用理论话说叫AOP 面向切面编程,可谓方便了太多需要异常处理的场景。说回Nestjs的异常过滤器,实现类似的功能,采用相似的处理方式...
-
6
If you haven't read the part-1, please first read that else you'll feel this given information is out of context In Part-2, I'l...
-
8
Nodejs CMS——基于 NestJS/NuxtJS 的完整开源项目这是一款轻量级的基于 Node.js 的开源 CMS,采用前后端分离开发模式,集成了 API、后台管理、WEB 展示三个完整项目。开箱即是一套完整的企...
-
7
A Guide to NestJS Swagger Configuration In this post, we...
-
7
A plugin enables a system to extend its core capabilities by providing a common foundation for developing them; it allows you to build modular, customizable, extensible, and easily maintainable applications.Use casesAllow...
-
9
什么是swagger?Swagger是一个简单但功能强大的API表达工具。它具有地球上最大的API工具生态系统,数以千计的开发人员,使用几乎所有的现代编程语言,都在支持和使用Swagger。使用...
-
6
API with NestJS #89. Replacing Express with Fastify We value your privacy We use coo...
-
9
Fast Development With NodeJS: NestJS BoilerplateNotificationsHappy Weekend, enjoy these top stories from this week, Kaiseki, PIRATES, and more 💚Last Saturday at 6:00 PMHappy Weekend...
-
11
Go将Gin整合Swagger自动生成API文档学习笔记 下载可执行文件go install github.com/swaggo/swag/cmd/[email protected] 在项目中下载依赖go get github.co...
-
8
主要分为express和koa2两个框架由于node后端学习,得有一份接口文档,个人不是很喜欢swagger 本文主要在于避坑一、网上科普文章多、此文主要解决遇到的问题
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK