单词详情同样使用GET
方式,用作获取单词的详细信息,会包含例句,中文翻译等列表中不存在的字段。
添加Api
api/words/v1/words.god
...
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"`
ProficiencyLevel uint `json:"proficiencyLevel"`
CreatedAt *gtime.Time `json:"createdAt"`
UpdatedAt *gtime.Time `json:"updatedAt"`
}
words/{id}
是一种模糊路由匹配方式,它会识别类似words/1
,words/2
,words/abc
这种路由,并将匹配到的值赋予Id
字段。Id
字段的类型是uint
,如果值不合法,则会使用uint
的零值。比如访问words/abc
,Id
字段的值就会是0
。
编写Logic
internal/logic/words/words.go
...
func Detail(ctx context.Context, uid, id uint) (word *entity.Words, err error) {
word = &entity.Words{}
db := dao.Words.Ctx(ctx).Where("id", id)
if uid > 0 {
db = db.Where("uid", uid)
}
err = db.Scan(word)
return
}
Controller调用Logic
internal/controller/words/words_v1_detail.go
package words
import (
"context"
"star/internal/logic/users"
"star/internal/logic/words"
"star/api/words/v1"
)
func (c *ControllerV1) Detail(ctx context.Context, req *v1.DetailReq) (res *v1.DetailRes, err error) {
uid, err := users.GetUid(ctx)
if err != nil {
return nil, err
}
word, err := words.Detail(ctx, uid, req.Id)
if err != nil {
return nil, err
}
return &v1.DetailRes{
Id: word.Id,
Word: word.Word,
Definition: word.Definition,
ExampleSentence: word.ExampleSentence,
ChineseTranslation: word.ChineseTranslation,
Pronunciation: word.Pronunciation,
ProficiencyLevel: word.ProficiencyLevel,
CreatedAt: word.CreatedAt,
UpdatedAt: word.UpdatedAt,
}, nil
}
接口测试
$ curl -X GET http://127.0.0.1:8000/v1/words/1 \
-H "Authorization: eyJhbGci...5U" \
-H "Content-Type: application/json" \
{
"code": 0,
"message": "",
"data": {
"id": 1,
"word": "example_update",
"definition": "A representative form or pattern.",
"exampleSentence": "This is an example sentence.",
"chineseTranslation": "例子",
"pronunciation": "ɪɡˈzɑːmp(ə)l",
"proficiencyLevel": 3,
"createdAt": "2024-11-14 15:40:54",
"updatedAt": "2024-11-14 16:09:37"
}
}