Golang,NodeJS(express和nestjs)自动生成swagger

getsu · · 1911 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

Golang 自动生成swagger

  1. 安装
    go get -u github.com/swaggo/swag/cmd/swag
  2. 在项目下执行swag init,会生成docs目录。如果目录存在则会报错。
  3. 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 acrhwfy@gmail.com

// @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框架集成

  1. 安装
npm i express-swagger-generator --save-dev

  1. 代码例:
  • 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 集成

  1. 安装
npm i --save @nestjs/swagger
  1. During the examination of the defined controllers, the SwaggerModule is looking for all used @Body(), @Query(), and @Param() decorators in the route handlers.
  2. 代码例
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();


有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:getsu

查看原文:Golang,NodeJS(express和nestjs)自动生成swagger

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1911 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传