Skip to main content
Version: 2.8.x(Latest)

The word detail also uses the GET method to retrieve detailed information of a word, including fields not present in the list such as example sentences and Chinese translations.

Add 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 uint `json:"proficiencyLevel"`
CreatedAt *gtime.Time `json:"createdAt"`
UpdatedAt *gtime.Time `json:"updatedAt"`
}

words/{id} is a form of fuzzy routing matching, which recognizes routes like words/1, words/2, and words/abc, and assigns the matched value to the Id field. The type of the Id field is uint, and if the value is invalid, it will use the zero value of uint. For example, accessing words/abc, the value of the Id field will be 0.

Write 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 Calls 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
}

Interface Testing


$ 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"
    }
}