使用的库

  • gin
  • gorm

开始

func Start() {
	router := gin.Default()
	apiV1 := router.Group("/api/v1/todo")
	{
		apiV1.POST("/", createTodo)
		apiV1.GET("/", fetchAllTodo)
		apiV1.GET("/:id", fetchSingleTodo)
		apiV1.PUT("/:id", updateTodo)
		apiV1.DELETE("/:id", deleteTodo)
	}
	router.Run()
}

定义Model

// 原始数据库字段
type todoModel struct {
	gorm.Model
	Title     string `json:"title"`
	Completed int    `json:"completed"`
}

// 处理返回的字段
type transformedTodo struct {
	ID        uint   `json:"id"`
	Title     string `json:"title"`
	Completed bool   `json:"completed"`
}

初始化数据库

var db *gorm.DB

func init() {
	var err error
	db, err = gorm.Open("mysql", "user:password@/demo?charset=utf8&parseTime=True&loc=Local")
	if err != nil {
		panic("failed to connect the database")
	}
	db.AutoMigrate(&todoModel{})
}

API:创建

func createTodo(context *gin.Context) {
	completed, _ := strconv.Atoi(context.PostForm("completed"))
	todo := todoModel{Title: context.PostForm("title"), Completed: completed}
	db.Save(&todo)
	context.JSON(http.StatusCreated, gin.H{
		"status":     http.StatusCreated,
		"message":    "Todo item created successfully!",
		"resourceId": todo.ID,
	})
}

API:获取所有列表

func fetchAllTodo(context *gin.Context) {
	var todos []todoModel
	var _todos []transformedTodo
	db.Find(&todos)
	if len(todos) == 0 {
		context.JSON(http.StatusNotFound, gin.H{
			"status":  http.StatusNotFound,
			"message": "No todo found",
		})
		return
	}
	for _, item := range todos {
		completed := item.Completed == 1
		_todos = append(_todos, transformedTodo{ID: item.ID, Title: item.Title, Completed: completed})
	}
	context.JSON(http.StatusOK, gin.H{
		"status": http.StatusOK,
		"data":   _todos,
	})
}

API:获取单个数据

func fetchSingleTodo(context *gin.Context) {
	var todo todoModel
	todoId := context.Param("id")
	db.First(&todo, todoId)
	if todo.ID == 0 {
		context.JSON(http.StatusNotFound, gin.H{
			"status":  http.StatusNotFound,
			"message": "No todo found",
		})
		return
	}
	completed := todo.Completed == 1
	_todo := transformedTodo{
		ID:        todo.ID,
		Title:     todo.Title,
		Completed: completed,
	}
	context.JSON(http.StatusOK, gin.H{
		"status": http.StatusOK,
		"data":   _todo,
	})
}

API:更新数据

func updateTodo(context *gin.Context) {
	var todo todoModel
	todoId := context.Param("id")
	db.First(&todo, todoId)
	if todo.ID == 0 {
		context.JSON(http.StatusNotFound, gin.H{
			"status":  http.StatusNotFound,
			"message": "No todo found",
		})
		return
	}
	//此处有问题
	db.Model(&todo).Update("title", context.PostForm("title"))
	completed, _ := strconv.Atoi(context.PostForm("completed"))
	db.Model(&todo).Update("completed", completed)
	context.JSON(http.StatusOK, gin.H{
		"status":  http.StatusOK,
		"message": "Todo updated successfully",
	})
}

API:删除数据

func deleteTodo(context *gin.Context) {
	var todo todoModel
	todoId := context.Param("id")
	db.First(&todo, todoId)
	if todo.ID == 0 {
		context.JSON(http.StatusNotFound, gin.H{
			"status":  http.StatusNotFound,
			"message": "No todo found",
		})
		return
	}
	db.Delete(&todo)
	context.JSON(http.StatusOK, gin.H{
		"status":  http.StatusOK,
		"message": "Todo deleted successfully",
	})
}

源码

https://github.com/jiangkang/JustGo