mcpField
E
encore-go-service

encore-go-service

github.com/encoredev开发30569 次安装2 天前更新
代码仓库

关于 encore-go-service

面向 Go 开发者的 Encore.go 应用服务与包组织指南,说明含 API 端点的包如何成为服务、服务间如何调用,以及共享辅助包的组织方式。

主要功能

  1. 01含 API 端点的包自动成为服务
  2. 02单服务与多服务布局
  3. 03按系统分组服务
  4. 04服务间直接调用
  5. 05共享非服务包

适用场景

  1. 01确定应用中的服务边界
  2. 02组织多服务 Go 项目
  3. 03安排可复用的辅助代码

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/encoredev/skills --skill encore-go-service

安装后在 Claude Code 中输入/encore-go-service确认已加载。

详细介绍

Encore.go 服务结构

说明

在 Encore.go 中,每个包含 API 端点的包都会自动成为一个服务。无需特殊配置。

创建服务

只需创建一个至少包含一个 //encore:api 端点的包:

// user/user.go
package user

import "context"

type User struct {
    ID    string `json:"id"`
    Email string `json:"email"`
    Name  string `json:"name"`
}

//encore:api public method=GET path=/users/:id
func GetUser(ctx context.Context, params *GetUserParams) (*User, error) {
    // This makes "user" a service
}
最小服务结构
user/
├── user.go          # API endpoints
├── db.go            # Database (if needed)
└── migrations/      # SQL migrations
    └── 1_create_users.up.sql

应用模式

单服务

应用可以在一个根服务包中定义其 API:

my-app/
├── encore.app
├── go.mod
├── api.go           # All endpoints
├── db.go            # Database
└── migrations/
    └── 1_initial.up.sql
多服务

每个服务都位于自己的包中:

my-app/
├── encore.app
├── go.mod
├── user/
│   ├── user.go
│   ├── db.go
│   └── migrations/
├── order/
│   ├── order.go
│   ├── db.go
│   └── migrations/
└── notification/
    └── notification.go
大型应用(基于系统)

将相关服务归入系统:

my-app/
├── encore.app
├── go.mod
├── commerce/
│   ├── order/
│   │   └── order.go
│   ├── cart/
│   │   └── cart.go
│   └── payment/
│       └── payment.go
├── identity/
│   ├── user/
│   │   └── user.go
│   └── auth/
│       └── auth.go
└── comms/
    ├── email/
    │   └── email.go
    └── push/
        └── push.go

服务间调用

只需直接导入并调用函数,Encore 会处理 RPC:

package order

import (
    "context"
    "encore.app/user"  // Import the user service
)

//encore:api auth method=GET path=/orders/:id
func GetOrderWithUser(ctx context.Context, params *GetOrderParams) (*OrderWithUser, error) {
    order, err := getOrder(ctx, params.ID)
    if err != nil {
        return nil, err
    }
    
    // This becomes an RPC call - Encore handles it
    orderUser, err := user.GetUser(ctx, &user.GetUserParams{ID: order.UserID})
    if err != nil {
        return nil, err
    }
    
    return &OrderWithUser{Order: order, User: orderUser}, nil
}

内部辅助代码(非服务包)

创建不包含 //encore:api 端点的包来存放共享代码:

my-app/
├── user/
│   └── user.go       # Service (has API)
├── order/
│   └── order.go      # Service (has API)
└── internal/
    ├── util/
    │   └── util.go   # Not a service (no API)
    └── validation/
        └── validate.go

指南

  • 包包含 //encore:api 端点时,就会成为服务
  • 服务不能嵌套在其他服务中
  • 跨服务调用看起来就像常规函数调用
  • 每个服务都可以拥有自己的数据库
  • 包名应使用小写且具有描述性
  • 不要仅为了组织代码而创建服务,请改用子包
  • 尚未确定服务边界时,请使用 encore-architecture

评论

支持 Markdown