关于 encore-go-api
面向 Go 开发者的 Encore Go API 端点编写指南,涵盖端点注解、请求与响应结构、参数映射及 HTTP 错误处理。
主要功能
- 01Encore API 注解
- 02请求与响应结构体模式
- 03路径、查询、标头和 Cookie 参数
- 04敏感数据脱敏
- 05HTTP 状态码与错误处理
适用场景
- 01创建需认证或公开的端点
- 02将请求数据映射到 Go 结构体
- 03对端点追踪中的敏感数据脱敏
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ encoredev/ skills --skill encore-go-api安装后在 Claude Code 中输入/encore-go-api确认已加载。
详细介绍
Encore Go API 端点
说明
使用 Encore Go 创建 API 端点时,请遵循以下模式:
1. 基本 API 端点
在函数上方使用 //encore:api 注解:
package user
import "context"
type GetUserParams struct {
ID string
}
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) {
// Implementation
return &User{ID: params.ID, Email: "[email protected]", Name: "John"}, nil
}
2. 带请求正文的 POST
type CreateUserParams struct {
Email string `json:"email"`
Name string `json:"name"`
}
//encore:api public method=POST path=/users
func CreateUser(ctx context.Context, params *CreateUserParams) (*User, error) {
// Implementation
return &User{ID: "new-id", Email: params.Email, Name: params.Name}, nil
}
API 注解选项
| 选项 | 值 | 说明 |
|---|---|---|
public | - | 可从外部访问 |
private | - | 只能由其他服务调用 |
auth | - | 需要身份验证 |
method | GET、POST、PUT、PATCH、DELETE | HTTP 方法 |
path | string | URL 路径,可使用 :param 表示路径参数 |
sensitive | - | 从跟踪记录中隐藏请求/响应载荷 |
示例
//encore:api public method=GET path=/health
//encore:api private method=POST path=/internal/process
//encore:api auth method=GET path=/profile
//encore:api public sensitive method=POST path=/auth/login
敏感数据
标记敏感字段,以便在跟踪日志中隐藏这些字段:
type LoginParams struct {
Email string `json:"email"`
Password string `json:"password" encore:"sensitive"`
}
也可以在注解中将整个端点标记为敏感:
//encore:api public sensitive method=POST path=/auth/login
func Login(ctx context.Context, params *LoginParams) (*TokenResponse, error) {
// Request and response will be redacted from traces
}
自定义 HTTP 状态码
使用 encore:"httpstatus" 标签返回自定义 HTTP 状态码:
type CreateResponse struct {
ID string `json:"id"`
Status int `encore:"httpstatus"`
}
//encore:api public method=POST path=/items
func CreateItem(ctx context.Context, params *CreateParams) (*CreateResponse, error) {
item := createItem(params)
return &CreateResponse{
ID: item.ID,
Status: 201, // Returns HTTP 201 Created
}, nil
}
请求参数来源
路径参数
// Path: /users/:id
type GetUserParams struct {
ID string // Automatically mapped from :id
}
查询参数
// Path: /users
type ListUsersParams struct {
Limit int `query:"limit"`
Offset int `query:"offset"`
}
//encore:api public method=GET path=/users
func ListUsers(ctx context.Context, params *ListUsersParams) (*ListResponse, error) {
// params.Limit and params.Offset come from query string
}
标头
type WebhookParams struct {
Signature string `header:"X-Webhook-Signature"`
Payload string `json:"payload"`
}
Cookie
import "net/http"
type AuthParams struct {
SessionCookie *http.Cookie `cookie:"session"`
CSRFToken string `header:"X-CSRF-Token"`
}
//encore:api auth method=POST path=/logout
func Logout(ctx context.Context, params *AuthParams) error {
// Access params.SessionCookie.Value
return nil
}
响应类型
标准响应
type Response struct {
Message string `json:"message"`
}
//encore:api public method=GET path=/hello
func Hello(ctx context.Context) (*Response, error) {
return &Response{Message: "Hello, World!"}, nil
}
无响应正文
//encore:api public method=DELETE path=/users/:id
func DeleteUser(ctx context.Context, params *DeleteParams) error {
// Return only error (no response body on success)
return nil
}
无请求参数
//encore:api public method=GET path=/health
func Health(ctx context.Context) (*HealthResponse, error) {
return &HealthResponse{Status: "ok"}, nil
}
错误处理
使用 errs 包返回正确的 HTTP 错误响应:
import "encore.dev/beta/errs"
//encore:api public method=GET path=/users/:id
func GetUser(ctx context.Context, params *GetUserParams) (*User, error) {
user, err := findUser(params.ID)
if err != nil {
return nil, err
}
if user == nil {
return nil, &errs.Error{
Code: errs.NotFound,
Message: "user not found",
}
}
return user, nil
}
常见错误代码
| 代码 | HTTP 状态 | 用途 |
|---|---|---|
errs.NotFound | 404 | 资源不存在 |
errs.InvalidArgument | 400 | 输入无效 |
errs.Unauthenticated | 401 | 缺少身份验证信息或身份验证无效 |
errs.PermissionDenied | 403 | 不允许执行此操作 |
errs.AlreadyExists | 409 | 资源重复 |
指南
- 在函数上方使用
//encore:api注解 - 请求参数必须是指向结构体的指针,也可以省略
- 响应必须是指向结构体的指针(无响应正文时可省略)
- 始终将
error作为最后一个返回值 - 使用结构体标签指定 JSON 字段名、查询参数和标头
- 路径参数会按名称自动映射到结构体字段
评论
支持 Markdown