encore-go-api
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseEncore Go API Endpoints
Encore Go API 端点
Instructions
操作说明
When creating API endpoints with Encore Go, follow these patterns:
使用Encore Go创建API端点时,请遵循以下模式:
1. Basic API Endpoint
1. 基础API端点
Use the annotation above your function:
//encore:apigo
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: "user@example.com", Name: "John"}, nil
}在函数上方使用注解:
//encore:apigo
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) {
// 实现逻辑
return &User{ID: params.ID, Email: "user@example.com", Name: "John"}, nil
}2. POST with Request Body
2. 带请求体的POST接口
go
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
}go
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) {
// 实现逻辑
return &User{ID: "new-id", Email: params.Email, Name: params.Name}, nil
}API Annotation Options
API注解选项
| Option | Values | Description |
|---|---|---|
| - | Accessible from outside |
| - | Only callable from other services |
| - | Requires authentication |
| GET, POST, PUT, PATCH, DELETE | HTTP method |
| string | URL path with |
| 选项 | 取值 | 说明 |
|---|---|---|
| - | 可从外部访问 |
| - | 仅可被其他服务调用 |
| - | 需要身份验证 |
| GET, POST, PUT, PATCH, DELETE | HTTP请求方法 |
| 字符串 | URL路径,使用 |
Examples
示例
go
//encore:api public method=GET path=/health
//encore:api private method=POST path=/internal/process
//encore:api auth method=GET path=/profilego
//encore:api public method=GET path=/health
//encore:api private method=POST path=/internal/process
//encore:api auth method=GET path=/profileRequest Parameter Sources
请求参数来源
Path Parameters
路径参数
go
// Path: /users/:id
type GetUserParams struct {
ID string // Automatically mapped from :id
}go
// 路径: /users/:id
type GetUserParams struct {
ID string // 自动从:id映射而来
}Query Parameters
查询参数
go
// 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
}go
// 路径: /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 和 params.Offset 来自查询字符串
}Headers
请求头参数
go
type WebhookParams struct {
Signature string `header:"X-Webhook-Signature"`
Payload string `json:"payload"`
}go
type WebhookParams struct {
Signature string `header:"X-Webhook-Signature"`
Payload string `json:"payload"`
}Raw Endpoints
原生端点
Use for webhooks or direct HTTP access:
//encore:api rawgo
import "net/http"
//encore:api public raw path=/webhooks/stripe method=POST
func StripeWebhook(w http.ResponseWriter, req *http.Request) {
sig := req.Header.Get("Stripe-Signature")
// Handle raw request...
w.WriteHeader(http.StatusOK)
}对于Webhook或直接HTTP访问,使用:
//encore:api rawgo
import "net/http"
//encore:api public raw path=/webhooks/stripe method=POST
func StripeWebhook(w http.ResponseWriter, req *http.Request) {
sig := req.Header.Get("Stripe-Signature")
// 处理原生请求...
w.WriteHeader(http.StatusOK)
}Response Types
响应类型
Standard Response
标准响应
go
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
}go
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
}No Response Body
无响应体
go
//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
}go
//encore:api public method=DELETE path=/users/:id
func DeleteUser(ctx context.Context, params *DeleteParams) error {
// 仅返回错误(成功时无响应体)
return nil
}No Request Parameters
无请求参数
go
//encore:api public method=GET path=/health
func Health(ctx context.Context) (*HealthResponse, error) {
return &HealthResponse{Status: "ok"}, nil
}go
//encore:api public method=GET path=/health
func Health(ctx context.Context) (*HealthResponse, error) {
return &HealthResponse{Status: "ok"}, nil
}Error Handling
错误处理
Use package for proper HTTP error responses:
errsgo
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错误响应:
errsgo
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
}Common Error Codes
常见错误码
| Code | HTTP Status | Usage |
|---|---|---|
| 404 | Resource doesn't exist |
| 400 | Bad input |
| 401 | Missing/invalid auth |
| 403 | Not allowed |
| 409 | Duplicate resource |
| 错误码 | HTTP状态码 | 用途 |
|---|---|---|
| 404 | 资源不存在 |
| 400 | 输入参数无效 |
| 401 | 缺少/无效的身份验证信息 |
| 403 | 无访问权限 |
| 409 | 资源已存在 |
Guidelines
开发规范
- Use annotation above the function
//encore:api - Request params must be a pointer to a struct or omitted
- Response must be a pointer to a struct (or omit for no body)
- Always return as the last return value
error - Use struct tags for JSON field names, query params, and headers
- Path parameters are automatically mapped to struct fields by name
- 在函数上方使用注解
//encore:api - 请求参数必须是结构体指针,或省略不写
- 响应必须是结构体指针(或省略表示无响应体)
- 始终将作为最后一个返回值
error - 使用结构体标签指定JSON字段名、查询参数和请求头参数
- 路径参数会根据名称自动映射到结构体字段