安装依赖
$ go get -u github.com/gin-gonic/gin
$ go get -u github.com/jinzhu/gorm
$ go get github.com/go-sql-driver/mysql
路由规划
POST todos/
GET todos/
GET todos/{id}
PUT todos/{id}
DELETE todos/{id}
完整源码
package main
import (
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"net/http"
"strconv"
)
type (
Todo struct {
gorm.Model
Title string `json:"title"`
Completed int `json:"completed"`
}
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", "root:123456@/demo?charset=utf8&parseTime=True&loc=Local")
if err != nil {
panic("failed to connect database")
}
// 自动迁移
db.AutoMigrate(&Todo{})
}
func createTodo(c *gin.Context) {
completed, _ := strconv.Atoi(c.PostForm("completed"))
todo := Todo{
Title: c.PostForm("title"),
Completed: completed,
}
db.Save(&todo)
c.JSON(http.StatusCreated, gin.H{"status": http.StatusCreated, "message": "Todo item created successfully!", "id": todo.ID})
}
func fetchAllTodo(c *gin.Context) {
var todos []Todo
var _todos []transformedTodo
db.Find(&todos)
if len(todos) <= 0 {
c.JSON(http.StatusNotFound, gin.H{"status": http.StatusNotFound, "message": "No todo found!"})
return
}
for _, todo := range todos {
completed := false
if todo.Completed == 1 {
completed = true
} else {
completed = false
}
_todos = append(_todos, transformedTodo{
ID: todo.ID,
Title: todo.Title,
Completed: completed,
})
}
c.JSON(http.StatusOK, gin.H{"status": http.StatusOK, "data": _todos})
}
func fetchSingleTodo(c *gin.Context) {
var todo Todo
id := c.Param("id")
db.First(&todo, id)
if todo.ID == 0 {
c.JSON(http.StatusNotFound, gin.H{"status": http.StatusNotFound, "message": "No todo found!"})
return
}
completed := false
if todo.Completed == 1 {
completed = true
} else {
completed = false
}
_todo := transformedTodo{
ID: todo.ID,
Title: todo.Title,
Completed: completed,
}
c.JSON(http.StatusOK, gin.H{"status": http.StatusOK, "data": _todo})
}
func deleteTodo(c *gin.Context) {
var todo Todo
id := c.Param("id")
db.First(&todo, id)
if todo.ID == 0 {
c.JSON(http.StatusNotFound, gin.H{"status": http.StatusNotFound, "message": "No todo found!"})
return
}
db.Delete(&todo)
c.JSON(http.StatusOK, gin.H{"status": http.StatusOK, "message": "Todo deleted successfully!"})
}
func updateTodo(c *gin.Context) {
var todo Todo
id := c.Param("id")
db.First(&todo, id)
if todo.ID == 0 {
c.JSON(http.StatusNotFound, gin.H{"status": http.StatusNotFound, "message": "No todo found!"})
return
}
completed, _ := strconv.Atoi(c.PostForm("completed"))
db.Model(&todo).Updates(Todo{Title: c.PostForm("title"), Completed: completed})
c.JSON(http.StatusOK, gin.H{"status": http.StatusOK, "message": "Todo updated successfully!"})
}
func main() {
defer db.Close()
router := gin.Default()
v1 := router.Group("/api/v1/todos")
{
v1.POST("/", createTodo)
v1.GET("/", fetchAllTodo)
v1.GET("/:id", fetchSingleTodo)
v1.PUT("/:id", updateTodo)
v1.DELETE("/:id", deleteTodo)
}
router.Run()
}
参考链接:https://medium.com/@thedevsaddam/build-restful-api-service-in-golang-using-gin-gonic-framework-85b1a6e176f3