Skip to content

Conversation

@sdfwds4
Copy link

@sdfwds4 sdfwds4 commented Jan 18, 2026

Feature: Add filename annotation to group API routes for generating api service code

What

  • Add support for filename annotation in @server block
  • Allow multiple API routes to generate into a single handler/logic file
  • Fully backward compatible - no changes when filename is not specified

Why

  • Better code organization for related operations (CQRS, read/write split)
  • Reduce file clutter in large projects
  • Improve maintainability by keeping related code together

How

  • Added filenameProperty constant to identify the annotation
  • Refactored genHandlers to aggregate routes by (subdir, filename) key
  • Refactored genLogic to aggregate routes by (subdir, filename) key
  • Updated templates to support rendering multiple handlers/logics per file
  • Import statements are automatically deduplicated

Example

See api/gogen/testdata/filename_demo.api for complete usage examples.

Testing

goctl api go -api api/gogen/testdata/filename_demo.api -dir ./output

Expected result:

  • Routes with same filename merge into one file
  • Routes without filename generate separately (traditional behavior)

@codecov
Copy link

codecov bot commented Jan 24, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Copy link
Contributor

@kevwan kevwan left a comment

Choose a reason for hiding this comment

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

Thanks for this feature! The filename annotation solves a real pain point with file proliferation in large APIs. The test data file (filename_demo.api) is excellent for demonstrating the use cases.

However, there are two important issues that need to be addressed before merging:

1. Missing Unit Tests

The PR lacks unit tests for the new aggregation logic. Please add tests covering:

  • Multiple routes with same filename - Verify they merge into one file correctly
  • Mixed scenarios - Some routes with filename annotation, some without
  • Import deduplication - Test that duplicate imports are properly handled
  • Edge cases:
    • Routes in different groups with same filename
    • SSE routes with filename annotation
    • Invalid filename values (special characters, path separators)

Suggested test file: tools/goctl/api/gogen/genhandlers_test.go and genlogic_test.go

2. Import Deduplication Implementation

The current string-based import deduplication (lines 74-91 in genhandlers.go and similar in genlogic.go) has potential issues:

for _, imp := range strings.Split(importsStr, "\n\t") {
    imp = strings.TrimSpace(imp)
    // ... string comparison
}

Problems:

  • Fragile parsing - depends on exact formatting from genHandlerImports()
  • Won't handle different import styles (e.g., "fmt" vs fmt "fmt" vs f "fmt")
  • Could fail with multi-line imports or comments

Suggestion: Consider using a map-based approach or Go's go/parser package for more robust deduplication:

importMap := make(map[string]bool)
for _, imp := range strings.Split(importsStr, "\n\t") {
    imp = strings.TrimSpace(imp)
    if len(imp) > 0 && !importMap[imp] {
        importMap[imp] = true
        f.imports = append(f.imports, imp)
    }
}

Or better yet, parse the import statements properly to handle aliased imports correctly.


Once these are addressed, this will be a great addition to goctl! 🚀

Copy link
Contributor

@kevwan kevwan left a comment

Choose a reason for hiding this comment

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

One more suggestion:

3. Use English in Demo Code

The test file filename_demo.api contains Chinese comments:

// Product - 商品资源
ProductReq {
    ProductId int64 `path:"productId"`
}

// Order - 订单流程
CreateOrderReq {
    ...
}

Please use English for all comments, type names, and documentation in the demo file. go-zero has an international user base, and English code examples ensure all contributors can understand and learn from them.

Suggested changes:

  • 商品资源Product Resource
  • 订单流程Order Workflow
  • 用户认证User Authentication
  • etc.

This aligns with the project's convention of maintaining English-first documentation for better international collaboration. 🌍

@sdfwds4
Copy link
Author

sdfwds4 commented Jan 25, 2026

@kevwan Thank you for the detailed review and valuable feedback! 🙏

I've addressed all the issues you mentioned:

1. ✅ Unit Tests Added

I've created comprehensive test coverage for the new aggregation logic:

genhandlers_test.go (7 tests):

  • Multiple routes with same filename merging into one file
  • Mixed scenarios (some routes with filename, some without)
  • Import deduplication verification
  • Routes in different groups with same filename (should remain separate)
  • SSE routes with filename annotation
  • Backward compatibility (without filename)

genlogic_test.go (8 tests):

  • Same coverage as handlers, plus additional edge cases:
    • Routes without request type
    • Routes without response type

All tests pass successfully ✅

2. ✅ Import Deduplication Improved

Replaced the string-based approach with a more robust map-based implementation:

importMap := make(map[string]bool)
for _, existing := range f.imports {
    importMap[existing] = true
}
for _, imp := range strings.Split(importsStr, "\n\t") {
    imp = strings.TrimSpace(imp)
    if len(imp) > 0 && !importMap[imp] {
        importMap[imp] = true
        f.imports = append(f.imports, imp)
    }
}

This approach is more efficient (O(n) vs O(n²)) and handles edge cases better.

3. ✅ Demo File Now in English

All Chinese comments in filename_demo.api have been translated to English:

  • Type comments: 商品资源Product Resource
  • Scenario descriptions: 场景1Scenario 1
  • @doc annotations: 创建商品Create product
  • Inline comments: all converted to English

The demo file is now fully accessible to the international community! 🌍


Thank you again for taking the time to review this PR thoroughly. The feedback has significantly improved the code quality and test coverage. Looking forward to your review of the updates! 🚀

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.

2 participants