---
title: "4.2.接口与控制器"
url: "https://goframe.org/course/proxima-book/gateway-controller"
markdown_url: "https://goframe.org/course/proxima-book/gateway-controller.md"
locale: "zh-Hans"
version: "2.10.x(Latest)"
section: "实战教程"
category: "实战教程 / proxima-book / 第四章-业务网关"
published: "2024-12-17"
updated: "2024-12-17"
description: "详细介绍了业务网关的 API 接口设计和控制器实现，包括用户登录、注册等接口的定义和请求处理逻辑。"
keywords: ["GoFrame", "API design", "gateway controller", "HTTP endpoints", "request validation", "response handling"]
---

# 4.2.接口与控制器

这一步大家应该很熟悉，就不过多介绍。

## Api
---
*app/gateway/api/user/v1/user.go*
```go
package v1  
  
import "github.com/gogf/gf/v2/frame/g"  
  
type LoginReq struct {  
    g.Meta   `path:"users/login" method:"post" sm:"登录" tags:"用户"`  
    Username string `json:"username" v:"required|length:3,12"`  
    Password string `json:"password" v:"required|length:6,16"`  
}  
  
type LoginRes struct {  
    Token string `json:"token" dc:"在需要鉴权的接口中header加入Authorization: token"` 
}
```

*app/gateway/api/words/v1/words.go*
```go
package v1  
  
import (  
    "github.com/gogf/gf/v2/frame/g"  
    "github.com/gogf/gf/v2/os/gtime"
)  
  
type CreateReq struct {  
    g.Meta     `path:"words" method:"post" sm:"创建" tags:"单词"`  
    Word       string `json:"word" v:"required|length:1,100" dc:"单词"`  
    Definition string `json:"definition" v:"required|length:1,300" dc:"单词定义"`  
}  
  
type CreateRes struct {  
}  
  
type DetailReq struct {  
    g.Meta `path:"words/{id}" method:"get" sm:"详情" tags:"单词"`  
    Id     uint `json:"id" v:"required"`  
}  
  
type DetailRes struct {  
    Id                 uint        `json:"id"`  
    Word               string      `json:"word"`  
    Definition         string      `json:"definition"`  
    ExampleSentence    string      `json:"exampleSentence"`  
    ChineseTranslation string      `json:"chineseTranslation"`  
    Pronunciation      string      `json:"pronunciation"`  
    CreatedAt          *gtime.Time `json:"createdAt"`  
    UpdatedAt          *gtime.Time `json:"updatedAt"`  
}
```

## Controller
---
执行命令，生成控制器。
```bash
$ gf gen ctrl
generated: D:\project\proxima\app\gateway\api\user\user.go
generated: D:\project\proxima\app\gateway\internal\controller\user\user.go
generated: D:\project\proxima\app\gateway\internal\controller\user\user_new.go
generated: D:\project\proxima\app\gateway\internal\controller\user\user_v1_login.go
generated: D:\project\proxima\app\gateway\api\words\words.go
generated: D:\project\proxima\app\gateway\internal\controller\words\words.go
generated: D:\project\proxima\app\gateway\internal\controller\words\words_new.go
generated: D:\project\proxima\app\gateway\internal\controller\words\words_v1_create.go
generated: D:\project\proxima\app\gateway\internal\controller\words\words_v1_detail.go
done!
