Skip to content

feat: Add i18n for apiserver.#68

Merged
iFurySt merged 1 commit into
mainfrom
feat/add-i18n-4-apiserver
May 14, 2025
Merged

feat: Add i18n for apiserver.#68
iFurySt merged 1 commit into
mainfrom
feat/add-i18n-4-apiserver

Conversation

@iFurySt
Copy link
Copy Markdown
Member

@iFurySt iFurySt commented May 13, 2025

Summary by Sourcery

Add comprehensive internationalization (i18n) support across the API server and web client, replacing hard-coded messages with translated responses and enabling language selection.

New Features:

  • Introduce internal/i18n package with go-i18n integration for loading and translating message catalogs
  • Add I18nError and ErrorWithCode types plus RespondWithError/RespondWithSuccess helpers for gin handlers
  • Implement axios interceptor and WebSocket URL parameter to include X-Lang header for language negotiation
  • Provide a LanguageSwitcher React component to change application language at runtime

Enhancements:

  • Refactor all API handler error and success flows to use i18n responses instead of manual c.JSON or toast calls
  • Centralize client error handling via new handleApiError utility and normalize API response data shapes
  • Add I18nConfig to server configuration and initialize translator in main.go

Build:

  • Update go.mod to include go-i18n, toml and related dependencies
  • Add translation files (en.toml and zh.toml) under configs/i18n

Documentation:

  • Add detailed documentation under docs/ illustrating backend and frontend i18n usage, error types, and translation file structure

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented May 13, 2025

Reviewer's Guide

This PR implements full internationalization support by introducing a backend i18n package with error/response helpers, initializing the translator at startup, refactoring all API handlers to use the new i18n methods, extending the frontend with language headers and centralized error handling, adding WebSocket language propagation, including English and Chinese translation files, updating dependencies, and shipping comprehensive documentation.

File-Level Changes

Change Details Files
Add backend i18n package with translation engine and response helpers
  • Implement I18n struct, translator initialization and TOML file loading
  • Define I18nError and ErrorWithCode types with template data support
  • Provide RespondWithError, RespondWithSuccess, SuccessResponse and ErrorResponse helpers
internal/i18n/core.go
internal/i18n/error.go
internal/i18n/response.go
internal/i18n/errorresponse.go
internal/i18n/const.go
Initialize global translator and configuration
  • Add I18nConfig to apiserver configuration struct
  • Call initI18n in cmd/apiserver/main.go with fallback path
  • Configure i18n path in configs/apiserver.yaml
internal/common/config/apiserver.go
cmd/apiserver/main.go
configs/apiserver.yaml
Refactor API handlers to use i18n helpers
  • Replace manual c.JSON error/success calls with i18n.RespondWithError and i18n.Success/Created
  • Switch from errors.New to predefined i18n.Error constants and WithParam
  • Simplify status-code logic by delegating to ErrorWithCode
internal/apiserver/handler/mcp.go
internal/apiserver/handler/auth.go
internal/apiserver/handler/tenant.go
internal/apiserver/handler/openapi.go
internal/apiserver/handler/chat.go
internal/apiserver/handler/websocket.go
Enhance frontend API layer with i18n integration
  • Add axios request interceptor to inject X-Lang and Authorization headers
  • Use a centralized handleApiError util in response interceptor
  • Normalize nested response.data and remove inline toast calls
web/src/services/api.ts
web/src/utils/error-handler.ts
Add language switcher component and WebSocket language support
  • Introduce LanguageSwitcher UI and hook into i18next.changeLanguage
  • Include lang query parameter in WebSocket client URL
  • Server reads X-Lang from query and sets context for translation
web/src/components/LanguageSwitcher.tsx
web/src/services/websocket.ts
internal/apiserver/handler/websocket.go
Add English and Chinese translation files
  • Create configs/i18n/en.toml with error and success message definitions
  • Create configs/i18n/zh.toml with corresponding translations
configs/i18n/en.toml
configs/i18n/zh.toml
Update documentation with comprehensive i18n guides
  • Add docs for usage examples, direct errors, middleware and summary
  • Document message naming conventions and template parameter syntax
docs/i18n_example.md
docs/i18n_direct_errors.md
docs/i18n.md
docs/i18n_summary.md
Update dependencies for i18n support
  • Add go-i18n/v2, BurntSushi/toml, x/text, tidwall/gjson modules
  • Remove duplicate entries and update go.mod/go.sum accordingly
go.mod
go.sum

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@iFurySt iFurySt marked this pull request as ready for review May 13, 2025 13:57
Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @iFurySt - I've reviewed your changes and they look great!

Here's what I looked at during the review
  • 🟡 General issues: 5 issues found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread web/src/services/api.ts
const response = await api.get('/mcp-servers', { params });
return response.data;
// 处理数据,兼容直接返回和嵌套在 data 中的情况
return response.data.data || response.data;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (bug_risk): The fallback to response.data may mask cases where data is intentionally null or falsy.

Switch to response.data.data ?? response.data so that only null or undefined values fall back, preserving valid falsy returns.

Suggested change
return response.data.data || response.data;
return response.data.data ?? response.data;

Comment thread web/src/services/api.ts
duration: 3000,
});
}
handleApiError(error, 'errors.fetch_mcp_servers');
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: handleApiError is used for most endpoints, but not for getUsers, getUser, and getUserWithTenants.

Switch error handling in getUsers, getUser, and getUserWithTenants to use handleApiError instead of toast.error to centralize handling and keep feedback consistent.

Comment thread web/src/services/api.ts
const response = await api.get('/auth/user');
return response.data.tenants || [];
// 处理数据,兼容直接返回和嵌套在 data 中的情况
const data = response.data.data || response.data;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: The same fallback logic as above may cause issues with falsy values.

Switch to response.data.data ?? response.data to avoid masking valid falsy values.

const token = window.localStorage.getItem('token');
this.ws = new WebSocket(`${import.meta.env.VITE_WS_BASE_URL}/chat?sessionId=${this.sessionId}&token=${token}`);
// Include language parameter in WebSocket URL
const lang = localStorage.getItem('i18nextLng') || 'zh';
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Default language fallback is hardcoded to 'zh', which may not match the application's default.

Use a shared constant or config value for the default language instead of hardcoding 'zh' to ensure consistent fallbacks across the app.

Comment thread internal/i18n/core.go
func GetTranslator() *I18n {
if translator == nil {
// Initialize with default path if not already initialized
_ = InitTranslator("configs/i18n")
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Implicit initialization of the translator may hide errors.

Log or propagate the InitTranslator error so failures don’t go unnoticed.

@iFurySt iFurySt merged commit 98ec1a8 into main May 14, 2025
@iFurySt iFurySt deleted the feat/add-i18n-4-apiserver branch May 14, 2025 02:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant