Skip to content
鼓励作者:欢迎打赏犒劳

thrift文件

注意:

  • 可以使用基本类型作为参数(如 i64, string)
  • 但只能有一个参数
  • 对于 GET 请求,基本类型从 query 或 path 取值是 OK 的
  • 对于 POST/PUT 等,必须使用 struct + api.body
  • 强烈推荐统一使用 struct 包装请求参数,这是企业级开发的最佳实践
  • 如果不写required或者optional,默认是optional

初体验

如果是post请求,传入的是对象,默认是 Content-Type: application/json

go
namespace go user

struct GetUserRequest {
    1: i64 user_id (api.query="user_id"),  // 查询参数
}
// 请求结构体:user_id 来自路径
struct GetUserRequest2 {
    1: i64 user_id (api.path="user_id"),  // 捕获路径中的 :user_id
}
// 用户状态枚举
enum UserStatus {
    INACTIVE = 0,
    ACTIVE = 1,
    BANNED = 2
}
struct GetUserResponse {
    1: i32 code,
    2: string msg,
    3: User user,
}

struct CreateUserRequest {
    1: optional string name (api.body="name"),     // 放在 body 中
    2: required string email (api.body="email"),
}

struct CreateUserResponse {
    1: i32 code,
    2: string msg,
    3: i64 user_id,
}

struct User {
    1: i64 id,
    2: string name,
    3: string email,
    4: UserStatus status,
}

// 定义服务,并绑定 HTTP 路由
service UserService {
    // GET /api/v1/user?user_id=123
    GetUserResponse GetUser(1: GetUserRequest req) (api.get="/api/v1/user"),

    // POST /api/v1/user
    CreateUserResponse CreateUser(1: CreateUserRequest req) (api.post="/api/v1/user"),
    
    // GET /api/v1/user/{user_id}
    GetUserResponse GetUser2(1: GetUserRequest2 req) (api.get="/api/v1/user/:user_id"),
    
    
    // GET /api/v1/user?user_id=123  支持,但是不推荐!!!
    GetUserResponse GetUserByInt(1: i64 user_id) (api.get="/api/v1/user"),
}

如有转载或 CV 的请标注本站原文地址