Build RESTful API service using Gin Web Framework

与蟒唯舞 · · 382 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

安装依赖
$ 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


有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:与蟒唯舞

查看原文:Build RESTful API service using Gin Web Framework

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

382 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传