---
title: "4.7.删除单词"
url: "https://goframe.org/course/starbook/word-delete"
markdown_url: "https://goframe.org/course/starbook/word-delete.md"
locale: "zh-Hans"
version: "2.10.x(Latest)"
section: "实战教程"
category: "实战教程 / starbook / 第四章-单词管理"
published: "2024-11-16"
updated: "2025-01-02"
description: "通过API实现单词删除功能，使用DELETE方法请求删除指定ID的单词。Logic层根据用户ID和单词ID进行数据库删除操作，控制器层负责接收请求并调用逻辑删除单词。提供了详细的接口测试步骤用于验证功能实现。"
keywords: ["GoFrame框架", "DELETE方法", "API删除单词", "Logic层实现", "接口开发", "控制器调用", "请求响应", "上下文管理", "路径参数", "数据库操作"]
---

# 4.7.删除单词

删除单词使用`DELETE`方式。
## 添加Api
---
*api/words/v1/words.go*
```go
...
type DeleteReq struct {  
    g.Meta `path:"words/{id}" method:"delete" sm:"删除" tags:"单词"`  
    Id     uint `json:"id" v:"required"`  
}  
  
type DeleteRes struct {  
}
```

## 编写Logic
---
*internal/logic/words/words.go*
```go
...

func (w *Words) Delete(ctx context.Context, uid, id uint) (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.Delete()  
    return  
}
```

## Controller调用Logic
---
*internal/controller/words/words_v1_delete.go*
```go
package words  
  
import (  
    "context"  
  
    "star/api/words/v1"
)  
  
func (c *ControllerV1) Delete(ctx context.Context, req *v1.DeleteReq) (res *v1.DeleteRes, err error) {  
    uid, err := c.users.GetUid(ctx)  
    if err != nil {  
       return nil, err  
    }  
  
    err = c.words.Delete(ctx, uid, req.Id)  
    return  
}
```

## 接口测试
---
```bash
$ curl -X DELETE http://127.0.0.1:8000/v1/words/1 \
     -H "Authorization: eyJhbGci...5U" \
     -H "Content-Type: application/json" \

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