使用 GoZero 框架实现一个简单的课程增删改查(CRUD)功能需要进行以下步骤:设置 GoZero 项目、定义数据模型、创建相应的 API 接口以及实现 CRUD 操作。下面是一个示例代码,包括基本的课程管理功能。
### 1. 安装 GoZero
首先,确保你的 Go 环境已安装 GoZero。你可以通过以下命令安装:
go get -u github.com/tal-tech/go-zero
### 2. 创建项目
使用 GoZero 创建一个新的项目:
go-zero new course
进入项目目录:
cd course
### 3. 定义数据模型
创建一个名为 `course.go` 的模型文件,定义课程的结构体和数据库操作方法:
// model/course.go
package modelimport ("github.com/tal-tech/go-zero/core/stores/sqlx"
)type Course struct {Id int64 `db:"id"` // 课程IDName string `db:"name"` // 课程名称Code string `db:"code"` // 课程代码
}type CourseModel struct {conn sqlx.SqlConn
}func NewCourseModel(conn sqlx.SqlConn) CourseModel {return CourseModel{conn: conn}
}func (m CourseModel) Insert(course Course) (int64, error) {result, err := m.conn.Exec("INSERT INTO course (name, code) VALUES (?, ?)", course.Name, course.Code)if err != nil {return 0, err}return result.LastInsertId()
}func (m CourseModel) Update(course Course) error {_, err := m.conn.Exec("UPDATE course SET name = ?, code = ? WHERE id = ?", course.Name, course.Code, course.Id)return err
}func (m CourseModel) Delete(id int64) error {_, err := m.conn.Exec("DELETE FROM course WHERE id = ?", id)return err
}func (m CourseModel) FindOne(id int64) (Course, error) {var course Courseerr := m.conn.QueryRow(&course, "SELECT id, name, code FROM course WHERE id = ?", id)return course, err
}func (m CourseModel) FindAll() ([]Course, error) {var courses []Courseerr := m.conn.QueryRows(&courses, "SELECT id, name, code FROM course")return courses, err
}
### 4. 创建数据库表
确保你的数据库中有一个 `course` 表。以下是 SQL 语句示例:
CREATE TABLE course (id INT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(255) NOT NULL,code VARCHAR(50) NOT NULL
);
### 5. 创建 API 处理程序
创建一个处理程序文件,例如 `courseHandler.go`,并实现 CRUD 接口:
// handler/courseHandler.go
package handlerimport ("net/http""github.com/tal-tech/go-zero/rest/httpx""your_project/model" // 根据你的项目路径更新"github.com/tal-tech/go-zero/core/logx"
)type CourseRequest struct {Id int64 `json:"id,omitempty"`Name string `json:"name"`Code string `json:"code"`
}func CreateCourseHandler(model model.CourseModel) http.HandlerFunc {return func(w http.ResponseWriter, r *http.Request) {var req CourseRequestif err := httpx.Parse(r, &req); err != nil {httpx.Error(w, err)return}course := model.Course{Name: req.Name, Code: req.Code}id, err := model.Insert(course)if err != nil {logx.Error(err)httpx.Error(w, err)return}httpx.OkJson(w, map[string]int64{"id": id})}
}func UpdateCourseHandler(model model.CourseModel) http.HandlerFunc {return func(w http.ResponseWriter, r *http.Request) {var req CourseRequestif err := httpx.Parse(r, &req); err != nil {httpx.Error(w, err)return}course := model.Course{Id: req.Id, Name: req.Name, Code: req.Code}if err := model.Update(course); err != nil {logx.Error(err)httpx.Error(w, err)return}httpx.Ok(w)}
}func DeleteCourseHandler(model model.CourseModel) http.HandlerFunc {return func(w http.ResponseWriter, r *http.Request) {id := r.URL.Query().Get("id")if err := model.Delete(id); err != nil {logx.Error(err)httpx.Error(w, err)return}httpx.Ok(w)}
}func FindCourseHandler(model model.CourseModel) http.HandlerFunc {return func(w http.ResponseWriter, r *http.Request) {id := r.URL.Query().Get("id")course, err := model.FindOne(id)if err != nil {logx.Error(err)httpx.Error(w, err)return}httpx.OkJson(w, course)}
}func FindAllCoursesHandler(model model.CourseModel) http.HandlerFunc {return func(w http.ResponseWriter, r *http.Request) {courses, err := model.FindAll()if err != nil {logx.Error(err)httpx.Error(w, err)return}httpx.OkJson(w, courses)}
}
### 6. 配置路由
在你的 `main.go` 文件中设置路由并启动 HTTP 服务器:
// main.go
package mainimport ("net/http""github.com/tal-tech/go-zero/rest""your_project/model" // 根据你的项目路径更新"your_project/handler" // 根据你的项目路径更新"github.com/tal-tech/go-zero/core/stores/sqlx"
)func main() {conn := sqlx.NewMysql("user:password@tcp(localhost:3306)/dbname") // 更新数据库连接信息courseModel := model.NewCourseModel(conn)r := rest.NewServer()defer r.Stop()r.AddRoute(rest.Route{Method: http.MethodPost,Path: "/courses",Handler: handler.CreateCourseHandler(courseModel),})r.AddRoute(rest.Route{Method: http.MethodPut,Path: "/courses",Handler: handler.UpdateCourseHandler(courseModel),})r.AddRoute(rest.Route{Method: http.MethodDelete,Path: "/courses",Handler: handler.DeleteCourseHandler(courseModel),})r.AddRoute(rest.Route{Method: http.MethodGet,Path: "/courses",Handler: handler.FindAllCoursesHandler(courseModel),})r.AddRoute(rest.Route{Method: http.MethodGet,Path: "/courses/{id}",Handler: handler.FindCourseHandler(courseModel),})r.Start()
}
### 7. 启动服务
使用以下命令运行你的 Go 应用:
go run main.go
### 8. 测试 API
使用工具如 `Postman` 或 `curl` 测试 API:
- **创建课程**:
curl -X POST http://localhost:8080/courses -d '{"name": "Go 101", "code": "G101"}'
- **更新课程**:
curl -X PUT http://localhost:8080/courses -d '{"id": 1, "name": "Go 102", "code": "G102"}'
- **删除课程**:
curl -X DELETE http://localhost:8080/courses?id=1
- **查找课程**:
```bash
curl -X GET http://localhost:8080/courses/1
```
- **查找所有课程**:
```bash
curl -X GET http://localhost:8080/courses
```
### 总结
以上示例展示了如何使用 GoZero 框架实现课程管理的基本 CRUD 操作。根据需要,您可以扩展和优化该示例,包括添加身份验证、错误处理、日志记录等功能。