温馨提示×

Debian Swagger如何支持API国际化

小樊
40
2025-11-02 19:18:20
栏目: 智能运维

1. 准备多语言资源文件
创建不同语言的资源文件(如messages_en.jsonmessages_zh.json),以键值对形式存储API文档中的文本(如标题、描述)。例如:

  • messages_en.json: {"swagger": {"info": {"title": "Debian API", "description": "API documentation for Debian"}}}
  • messages_zh.json: {"swagger": {"info": {"title": "Debian API文档", "description": "Debian应用的API文档"}}}
    资源文件需集中存放(如src/main/resources/i18n/),便于统一管理。

2. 安装必要依赖
根据项目技术栈安装国际化及Swagger相关依赖。以Node.js(Express)为例,需安装:

npm install swagger-jsdoc swagger-ui-express i18next i18next-http-middleware --save

以Spring Boot(Java)为例,需在pom.xml中添加:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

依赖需匹配项目技术栈(如Spring Boot需对应版本,Node.js需对应框架)。

3. 配置Swagger基础定义
在Swagger配置文件(如swagger.js)中,使用占位符替代静态文本(如${swagger.info.title}),以便后续动态替换为本地化内容。例如:

const swaggerJsDoc = require('swagger-jsdoc');
const swaggerOptions = {
    swaggerDefinition: {
        info: {
            title: '${swagger.info.title}', // 占位符
            description: '${swagger.info.description}', // 占位符
            version: '1.0.0'
        },
        servers: [{'url': 'http://localhost:3000'}]
    },
    apis: ['./routes/*.js'] // 指定API路由文件
};
const swaggerDocs = swaggerJsDoc(swaggerOptions);
module.exports = swaggerDocs;

对于Spring Boot,可通过@Operation注解的summarydescription属性引用资源键(如@Operation(summary = "${api.operation.summary}"))。

4. 集成国际化库
使用i18next(Node.js)或MessageSource(Spring Boot)加载资源文件并管理语言切换。

  • Node.js示例
const i18next = require('i18next');
const Backend = require('i18next-fs-backend');
const middleware = require('i18next-http-middleware');

i18next.use(Backend).use(middleware.LanguageDetector).init({
    fallbackLng: 'en', // 默认语言
    backend: {
        loadPath: './src/main/resources/i18n/{{lng}}.json' // 资源文件路径
    },
    debug: true
});
  • Spring Boot示例
@Configuration
public class InternationalizationConfig {
    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:i18n/messages"); // 资源文件基路径
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver localeResolver = new SessionLocaleResolver();
        localeResolver.setDefaultLocale(Locale.US); // 默认语言
        return localeResolver;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
        interceptor.setParamName("lang"); // 语言切换参数(如?lang=zh)
        registry.addInterceptor(interceptor);
    }
}

集成后,库会根据用户语言偏好(如浏览器设置、URL参数)自动加载对应资源文件。

5. 动态替换Swagger内容
在Swagger配置中,通过国际化库获取本地化文本并替换占位符。

  • Node.js示例
const swaggerUi = require('swagger-ui-express');
const app = express();

app.use('/api-docs', swaggerUi.serve, (req, res) => {
    const { lng } = req.query; // 获取URL语言参数(如?lng=zh)
    i18next.changeLanguage(lng || 'en').then(() => {
        const localizedDocs = swaggerDocs;
        localizedDocs.swaggerDefinition.info.title = i18next.t('swagger.info.title');
        localizedDocs.swaggerDefinition.info.description = i18next.t('swagger.info.description');
        res.render('swagger-ui', { ui: swaggerUi.setup(localizedDocs) });
    });
});
  • Spring Boot示例
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Autowired
    private MessageSource messageSource;

    @Bean
    public Docket api() {
        Locale locale = LocaleContextHolder.getLocale(); // 获取当前语言环境
        String title = messageSource.getMessage("swagger.info.title", null, locale);
        String description = messageSource.getMessage("swagger.info.description", null, locale);

        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(new ApiInfoBuilder()
                        .title(title)
                        .description(description)
                        .version("1.0.0")
                        .build());
    }
}

动态替换确保Swagger UI显示的内容与用户语言偏好一致。

6. 测试多语言功能
启动应用后,访问Swagger UI(如http://localhost:3000/api-docs),通过以下方式切换语言:

  • URL参数http://localhost:3000/api-docs?lng=zh(强制切换为中文);
  • 浏览器设置:修改浏览器语言偏好(如Chrome设置为中文),Swagger UI会自动适配。
    验证标题、描述等文本是否显示为对应语言,确保无乱码或错误。

0