encore-go-api

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Encore 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
//encore:api
annotation above your function:
go
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:api
注解:
go
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注解选项

OptionValuesDescription
public
-Accessible from outside
private
-Only callable from other services
auth
-Requires authentication
method
GET, POST, PUT, PATCH, DELETEHTTP method
path
stringURL path with
:param
for path params
选项取值说明
public
-可从外部访问
private
-仅可被其他服务调用
auth
-需要身份验证
method
GET, POST, PUT, PATCH, DELETEHTTP请求方法
path
字符串URL路径,使用
:param
表示路径参数

Examples

示例

go
//encore:api public method=GET path=/health
//encore:api private method=POST path=/internal/process
//encore:api auth method=GET path=/profile
go
//encore:api public method=GET path=/health
//encore:api private method=POST path=/internal/process
//encore:api auth method=GET path=/profile

Request 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
//encore:api raw
for webhooks or direct HTTP access:
go
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 raw
go
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
errs
package for proper HTTP error responses:
go
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
}
使用
errs
包返回标准的HTTP错误响应:
go
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

常见错误码

CodeHTTP StatusUsage
errs.NotFound
404Resource doesn't exist
errs.InvalidArgument
400Bad input
errs.Unauthenticated
401Missing/invalid auth
errs.PermissionDenied
403Not allowed
errs.AlreadyExists
409Duplicate resource
错误码HTTP状态码用途
errs.NotFound
404资源不存在
errs.InvalidArgument
400输入参数无效
errs.Unauthenticated
401缺少/无效的身份验证信息
errs.PermissionDenied
403无访问权限
errs.AlreadyExists
409资源已存在

Guidelines

开发规范

  • Use
    //encore:api
    annotation above the function
  • 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
    error
    as the last return value
  • 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字段名、查询参数和请求头参数
  • 路径参数会根据名称自动映射到结构体字段