单词详情同样使用GET方式,用作获取单词的详细信息,会包含例句,中文翻译等列表中不存在的字段。
添加Api
api/words/v1/words.go
...
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   ProficiencyLevel `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 (w *Words) Detail(ctx context.Context, uid, id uint) (word *entity.Words, err error) {  
    var (  
       cls = dao.Words.Columns()  
       orm = dao.Words.Ctx(ctx)  
    )  
    orm = orm.Where(cls.Id, id)  
    if uid > 0 {  
       orm = orm.Where(cls.Uid, uid)  
    }  
    err = orm.Scan(&word)  
    return  
}
Controller调用Logic
internal/controller/words/words_v1_detail.go
package words  
  
import (  
    "context"  
  
    "star/api/words/v1"
)  
  
func (c *ControllerV1) Detail(ctx context.Context, req *v1.DetailReq) (res *v1.DetailRes, err error) {  
    uid, err := c.users.GetUid(ctx)  
    if err != nil {  
        return nil, err  
    }  
  
    word, err := c.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:   v1.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"
    }
}