跳到主要内容
版本:2.8.x(Latest)

查询单词分页列表使用GET方式,并且提供一些入参:

字段名类型jsonvalid描述
Wordstringjson:"word"length:1,100模糊查询单词
Pageintjson:"page"min:1页码,默认1
Sizeintjson:"size"between:1,100每页数量,默认10

添加Api


定义一个结构体List保存一个单词的字段。在ListRes中返回一个List切片,表示单词列表,Total表示所有单词数量,返回给前端方便做分页操作。

api/words/v1/words.go

...

type List struct {
Id uint `json:"id"`
Word string `json:"word"`
Definition string `json:"definition"`
ProficiencyLevel model.ProficiencyLevel `json:"proficiencyLevel"`
}

type ListReq struct {
g.Meta `path:"words" method:"get" sm:"列表" tags:"单词"`
Word string `json:"word" v:"length:1,100" dc:"模糊查询单词"`
Page int `json:"page" v:"min:1" dc:"页码,默认1"`
Size int `json:"size" v:"between:1,100" dc:"每页数量,默认10"`
}

type ListRes struct {
List []List `json:"list"`
Total uint `json:"total"`
}

编写Logic


internal/logic/words/words.go

...

type ListInput struct {
Uid uint
Word string
Page int
Size int
}

func (w *Words) List(ctx context.Context, in ListInput) (list []entity.Words, total int, err error) {
// 对于查询初始值的处理
if in.Page == 0 {
in.Page = 1
}
if in.Size == 0 {
in.Size = 15
}

var (
cls = dao.Words.Columns()
orm = dao.Words.Ctx(ctx)
)
// 组成查询链
if in.Uid > 0 {
orm = orm.Where(cls.Uid, in.Uid)
}

// 模糊查询
if len(in.Word) != 0 {
orm = orm.WhereLike(cls.Word, "%"+in.Word+"%")
}
orm = orm.OrderDesc(cls.CreatedAt).OrderDesc(cls.Id).Page(in.Page, in.Size)
if err = orm.ScanAndCount(&list, &total, true); err != nil {
return
}
return
}

上述代码用到了orm.WhereLike(cls.Word, "%"+in.Word+"%"),它是模糊查询的意思,最终会生成word LIKE '%{word}%' 子句。

AllAndCount用于同时查询数据记录列表及总数量,一般用于分页查询场景中,简化分页查询逻辑。

Controller调用Logic


internal/controller/words/words_v1_list.go

package words  

import (
"context"

"star/api/words/v1"
"star/internal/logic/words"
)

func (c *ControllerV1) List(ctx context.Context, req *v1.ListReq) (res *v1.ListRes, err error) {
uid, err := c.users.GetUid(ctx)
if err != nil {
return nil, err
}
wordList, total, err := c.words.List(ctx, words.ListInput{
Uid: uid,
Word: req.Word,
Page: req.Page,
Size: req.Size,
})
if err != nil {
return nil, err
}

var list []v1.List
for _, v := range wordList {
list = append(list, v1.List{
Id: v.Id,
Word: v.Word,
Definition: v.Definition,
ProficiencyLevel: v1.ProficiencyLevel(v.ProficiencyLevel),
})
}

return &v1.ListRes{
List: list,
Total: uint(total),
}, nil
}

接口测试


$ curl -X GET http://127.0.0.1:8000/v1/words \
-H "Authorization: eyJhbGci...5U" \
-H "Content-Type: application/json" \

{
    "code": 0,
    "message": "",
    "data": {
        "list": [
            {
                "id": 1,
                "word": "example_update",
                "definition": "A representative form or pattern.",
                "proficiencyLevel": 3
            }
        ],
        "total": 1
    }
}