---
title: "4.3.新增单词"
url: "https://goframe.org/course/starbook/word-create"
markdown_url: "https://goframe.org/course/starbook/word-create.md"
locale: "zh-Hans"
version: "2.10.x(Latest)"
section: "实战教程"
category: "实战教程 / starbook / 第四章-单词管理"
published: "2024-11-16"
updated: "2025-05-14"
description: "使用GoFrame框架实现RESTful风格的单词创建API，包括架构设计中的API层和逻辑层的职责划分，强调数据结构不宜透传。详细解说如何在逻辑层中确保数据的一致性并避免重复输入，以及在控制器中调用多层逻辑以保持功能单一。此外，还涵盖了控制器的路由注册及接口测试的方法。"
keywords: ["GoFrame", "RESTful", "API", "单词创建", "数据接收层", "逻辑操作层", "数据模型", "数据库一致性", "单词表", "控制器注册"]
---

# 4.3.新增单词

根据`RESTful`风格，新增应该使用`POST`方式，祭出我们的三板斧，无情的搬砖式开发。
## 添加 Api
---
*api/words/v1/words.go*
```go
type ProficiencyLevel uint  
  
const (  
    ProficiencyLevel1 ProficiencyLevel = iota + 1  
    ProficiencyLevel2  
    ProficiencyLevel3
    ProficiencyLevel4
    ProficiencyLevel5
)

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:"单词定义"`  
    ExampleSentence    string           `json:"example_sentence" v:"required|length:1,300" dc:"例句"`  
    ChineseTranslation string           `json:"chinese_translation" v:"required|length:1,300" dc:"中文翻译"`  
    Pronunciation      string           `json:"pronunciation" v:"required|length:1,100" dc:"发音"`  
    ProficiencyLevel   ProficiencyLevel `json:"proficiency_level" v:"required|between:1,5" dc:"熟练度，1最低，5最高"`  
}  
  
type CreateRes struct {  
}
```

在这里我们自定义了一个数据类型`ProficiencyLevel`，表示单词的掌握程度，并定义了五个枚举值：`ProficiencyLevel1-5`从低到高表示级别。

这种自定义类型加上固定枚举值的方式是一种高级的程序设计技巧，可以广泛用在各类状态上，比如订单状态，项目阶段等。新手在编程总喜欢使用`int`一把梭，最后造成代码里全是`1,2,3...`这种数字状态，导致代码的可读性和可维护性较差。

## 编写Logic
---
同样的，定义`Words`对象，新建`New`函数用作实例化。

*internal/logic/words/words.go*
```go
package words

type Words struct {  
}  
  
func New() *Words {  
    return &Words{}  
}
```

*internal/logic/words/words.go*
```go
...

type CreateInput struct {  
    Uid                uint  
    Word               string  
    Definition         string  
    ExampleSentence    string  
    ChineseTranslation string  
    Pronunciation      string  
    ProficiencyLevel   v1.ProficiencyLevel  
}  
  
func (w *Words) Create(ctx context.Context, in CreateInput) error {  
    var cls = dao.Words.Columns()  
  
    count, err := dao.Words.Ctx(ctx).  
       Where(cls.Uid, in.Uid).  
       Where(cls.Word, in.Word).Count()  
    if err != nil {  
       return err  
    }  
    if count > 0 {  
       return gerror.New("单词已存在")  
    }  
  
    _, err = dao.Words.Ctx(ctx).Data(do.Words{  
       Uid:                in.Uid,  
       Word:               in.Word,  
       Definition:         in.Definition,  
       ExampleSentence:    in.ExampleSentence,  
       ChineseTranslation: in.ChineseTranslation,  
       Pronunciation:      in.Pronunciation,  
       ProficiencyLevel:   in.ProficiencyLevel,  
    }).Insert()  
    if err != nil {  
       return err  
    }  
    return nil  
}
```

在`Logic`中我们也需要确保同一用户单词不能重复，和数据库保持一致。

### account logic
单词表中保存有`uid`字段，我们需要在`logic/users`包中封装一个`GetUid`函数提供`uid`。

*internal/logic/users/users_account.go*
```go
func (u *Users) GetUid(ctx context.Context) (uint, error) {  
    user, err := u.Info(ctx)  
    if err != nil {  
       return 0, err  
    }  
    return user.Id, nil  
}
```

## Controller调用Logic
---
在创建单词的控制器中，我们需要调用`account`和`words`两个`logic`，我们将他封装到控制器中。

*internal/controller/words/words_new.go*
```go
...

package words  
  
import (  
    "star/api/words"  
    usersLogic "star/internal/logic/users"  
    wordsLogic "star/internal/logic/words"  
)  
  
type ControllerV1 struct {  
    users *usersLogic.Users  
    words *wordsLogic.Words  
}  
  
func NewV1() words.IWordsV1 {  
    return &ControllerV1{  
        users: usersLogic.New(),  
        words: wordsLogic.New(),  
    }  
}
```

*internal/controller/words/words_v1_create.go*
```go
package words  
  
import (  
    "context"  
  
    "star/api/words/v1"
    "star/internal/logic/words"
)  
  
func (c *ControllerV1) Create(ctx context.Context, req *v1.CreateReq) (res *v1.CreateRes, err error) {  
    uid, err := c.users.GetUid(ctx)  
    if err != nil {  
       return nil, err  
    }  
    err = c.words.Create(ctx, words.CreateInput {  
       Uid:                uid,  
       Word:               req.Word,  
       Definition:         req.Definition,  
       ExampleSentence:    req.ExampleSentence,  
       ChineseTranslation: req.ChineseTranslation,  
       Pronunciation:      req.Pronunciation,  
       ProficiencyLevel:   req.ProficiencyLevel, 
    })  
    return nil, err  
}
```

在`Controller`中调用两个`Logic`层级的方法：`users.GetUid`和`words.Create`来实现功能。注意，不要在`words.Create`中直接调用`users.GetUid`，这样会加重`words`包的耦合。

最佳实验是，**尽量保证`Logic`函数的功能单一化，在`Controller`中多次调用`Logic`完成功能。** 

## 注册控制器
---
*internal/cmd/cmd.go*
```go
package cmd  

...

var (  
    Main = gcmd.Command{  
       Name:  "main",  
       Usage: "main",  
       Brief: "start http server",  
       Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {  
          s := g.Server()  
          s.Group("/", func(group *ghttp.RouterGroup) {  
             group.Middleware(ghttp.MiddlewareHandlerResponse)  
             group.Group("/v1", func(group *ghttp.RouterGroup) {  
                group.Bind(  
                   users.NewV1(),  
                )  
                group.Group("/", func(group *ghttp.RouterGroup) {  
                   group.Middleware(middleware.Auth)  
                   group.Bind(  
                      account.NewV1(),  
                      words.NewV1(),  
                   )  
                })  
             })  
          })  
          s.Run()  
          return nil  
       },  
    }  
)
```

控制器注册到与`account.NewV1()`同一个路由组下，确保能经过`Auth`中间件。

## 接口测试
---
```bash
$ curl -X POST http://127.0.0.1:8000/v1/words \
     -H "Authorization: eyJhbGci...5U" \
     -H "Content-Type: application/json" \
     -d '{
           "word": "example",
           "definition": "A representative form or pattern.",
           "example_sentence": "This is an example sentence.",
           "chinese_translation": "例子",
           "pronunciation": "ɪɡˈzɑːmp(ə)l",
           "proficiency_level": 3
         }'

{
    "code": 0,
    "message": "",
    "data": null
}
```

执行命令，查询数据是否正常添加：
```sql
$ SELECT * FROM words;
```

| id  | uid | word    | definition                        | example_sentence             | chinese_translation | pronunciation | proficiency_level | created_at          | updated_at          |
| --- | --- | ------- | --------------------------------- | ---------------------------- | ------------------- | ------------- | ----------------- | ------------------- | ------------------- |
| 1   | 1   | example | A representative form or pattern. | This is an example sentence. | 例子                  | ɪɡˈzɑːmp(ə)l  | 3                 | 2024/11/12 15:38:50 | 2024/11/12 15:38:50 |
