在Linux环境下实现Swagger API文档的国际化可以通过以下几种方法:
npm install swagger-ui-dist --save
<script src="node_modules/swagger-ui-dist/swagger-ui-bundle.js"></script>
<script src="node_modules/swagger-ui-dist/swagger-ui-standalone-preset.js"></script>
<script>
window.onload = function() {
const ui = SwaggerUIBundle({
url: "your-api-spec.json",
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout",
// 设置语言
locale: "zh-CN" // 可替换为其他语言代码如 en, fr, ja等
});
}
</script>
api_spec_en.json
, api_spec_zh.json
, api_spec_ja.json
,并在每个文件中使用相应语言的描述信息。const express = require('express');
const app = express();
const swaggerJsdoc = require('swagger-jsdoc');
app.get('/api-docs', (req, res) => {
const acceptLanguage = req.headers['accept-language'] || 'en';
const options = {
definition: {
openapi: '3.0.0',
info: {
title: getLocalizedTitle(acceptLanguage),
description: getLocalizedDescription(acceptLanguage),
version: '1.0.0',
},
},
apis: ['./routes/*.js'],
};
const specs = swaggerJsdoc(options);
res.json(specs);
});
function getLocalizedTitle(lang) {
const titles = {
'en': 'API Documentation',
'zh': 'API文档',
'ja': 'APIドキュメント'
};
return titles[lang] || titles['en'];
}
function getLocalizedDescription(lang) {
const descriptions = {
'en': 'This is the API documentation for our application.',
'zh': '这是我们应用程序的API文档。',
'ja': 'これが私たちのアプリケーションのAPIドキュメントです。'
};
return descriptions[lang] || descriptions['en'];
}
npm install i18n --save
const i18n = require('i18n');
i18n.configure({
locales: ['en', 'zh', 'ja'],
directory: __dirname + '/locales',
defaultLocale: 'en'
});
const swaggerOptions = {
info: {
title: i18n.__('API Documentation'),
description: i18n.__('API description goes here')
}
};
location /api-docs {
if ($http_accept_language ~* "^zh") {
rewrite ^ /api-docs/zh last;
}
if ($http_accept_language ~* "^ja") {
rewrite ^ /api-docs/ja last;
}
rewrite ^ /api-docs/en last;
}
@Bean
public OpenAPI customOpenAPI(LocaleResolver localeResolver) {
return new OpenAPI()
.info(new Info()
.title(getLocalizedTitle(localeResolver))
.description(getLocalizedDescription(localeResolver)));
}
private String getLocalizedTitle(LocaleResolver localeResolver) {
Locale locale = localeResolver.resolveLocale(null);
ResourceBundle bundle = ResourceBundle.getBundle("messages", locale);
return bundle.getString("api.title");
}