package main

import (
"net/http" "github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
) func Database() *gorm.DB {
//open a db connection
db, err := gorm.Open("mysql", "root:pass@tcp(127.0.0.1:8889)/gotest?parseTime=true")
if err != nil {
panic("failed to connect database")
}
return db
} func main() { //Migrate the schema
db := Database()
db.AutoMigrate(&Product{})
router := gin.Default()
router.GET("/", startPage)
router.LoadHTMLGlob("templates/*")
v1 := router.Group("/api/v1/")
{
v1.POST("product/", CreateProduct)
v1.GET("product/", FetchAllProduct)
v1.GET("product/:id", FetchSingleProduct)
v1.PUT("product/:id", UpdateProduct)
v1.DELETE("product/:id", DeleteProduct)
}
router.Run() } type Product struct {
gorm.Model
Name string `json:"name"`
Description string `json:"description"`
Images string `json:"images"`
Price string `json:"price"`
} type TransformedProduct struct {
ID uint `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Images string `json:"images"`
Price string `json:"price"`
} func CreateProduct(c *gin.Context) { product := Product{
Name: c.PostForm("name"),
Description: c.PostForm("description"),
Images: c.PostForm("images"),
Price: c.PostForm("price"),
}
db := Database()
db.Save(&product)
c.JSON(http.StatusCreated, gin.H{"status": http.StatusCreated, "message": "Product item created successfully!", "resourceId": product.ID})
} func FetchAllProduct(c *gin.Context) {
var products []Product
var _products []TransformedProduct db := Database()
db.Find(&products) if len(products) <= 0 {
c.JSON(http.StatusNotFound, gin.H{"status": http.StatusNotFound, "message": "No todo found!"})
return
} //transforms the todos for building a good response
for _, item := range products {
_products = append(
_products, TransformedProduct{
ID: item.ID,
Name: item.Name,
Description: item.Description,
Images: item.Images,
Price: item.Price,
})
}
c.JSON(http.StatusOK, gin.H{"status": http.StatusOK, "data": _products})
} func FetchSingleProduct(c *gin.Context) {
var product Product
productId := c.Param("id") db := Database()
db.First(&product, productId) if product.ID == 0 {
c.JSON(http.StatusNotFound, gin.H{"status": http.StatusNotFound, "message": "No product found!"})
return
} _product := TransformedProduct{
ID: product.ID,
Name: product.Name,
Description: product.Description,
Images: product.Images,
Price: product.Price,
}
c.JSON(http.StatusOK, gin.H{"status": http.StatusOK, "data": _product})
} func UpdateProduct(c *gin.Context) {
var product Product
tproductId := c.Param("id")
db := Database()
db.First(&product, tproductId) if product.ID == 0 {
c.JSON(http.StatusNotFound, gin.H{"status": http.StatusNotFound, "message": "No product found!"})
return
} db.Model(&product).Update("name", c.PostForm("name"))
db.Model(&product).Update("descroption", c.PostForm("descroption"))
db.Model(&product).Update("images", c.PostForm("images"))
db.Model(&product).Update("price", c.PostForm("price"))
c.JSON(http.StatusOK, gin.H{"status": http.StatusOK, "message": "Product updated successfully!"})
} func DeleteProduct(c *gin.Context) {
var product Product
productId := c.Param("id")
db := Database()
db.First(&product, productId) if product.ID == 0 {
c.JSON(http.StatusNotFound, gin.H{"status": http.StatusNotFound, "message": "No product found!"})
return
} db.Delete(&product)
c.JSON(http.StatusOK, gin.H{"status": http.StatusOK, "message": "product deleted successfully!"})
} func startPage(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl", gin.H{
"title": "simple api gin",
})
}

golang rest api example的更多相关文章

  1. Golang面向API编程-interface(接口)

    Golang面向API编程-interface(接口) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. Golang并不是一种典型的面向对象编程(Object Oriented Pr ...

  2. golang esl api

    通过ESL 调取FS的状态,比如show calls : 用golang  eventsocket 实现 conn, err := eventsocket.Dial("192.168.5.3 ...

  3. golang restful api

    https://medium.com/@petrousov/how-to-build-a-restful-api-in-go-for-phonebook-app-d55f7234a10 ------- ...

  4. Golang Gateway API 搭建教程

    原文链接 随着微服务的兴起,行业里出现了非常多优秀的微服务网关框架,今天教大家搭建一套国人,用Golang写的微服务网关框架. 这里啰嗦一句,可能到今天还有人不理解什么是微服务,为什么要用微服务.目前 ...

  5. golang gin框架 使用swagger生成api文档

    github地址:https://github.com/swaggo/gin-swagger 1.下载swag $ go get -u github.com/swaggo/swag/cmd/swag ...

  6. Golang下通过syscall调用win32的dll(calling Windows DLLs from Go )

    很多同学比如我虽然很喜欢golang,但是还是需要调用很多遗留项目或者其他优秀的开源项目,这时怎么办呢?我们想到的方法是用package里的syscall结合cgo 注意此处有坑: 在我调试时显示no ...

  7. 在Golang中获取系统的磁盘空间内存占用

    获取磁盘占用情况(Linux/Mac下有效) import ( "syscall" ) type DiskStatus struct { All uint64 `json:&quo ...

  8. golang包快速生成base64验证码

    base64Captcha快速生成base64编码图片验证码字符串 支持多种样式,算术,数字,字母,混合模式,语音模式. Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一.Base6 ...

  9. golang web 方案

    概要 开发 web 框架 数据库 认证 日志 配置 静态文件服务 上传/下载 发布 docker 打包 部署中遇到的问题 时区问题 概要 轻量的基于 golang 的 web 开发实践. golang ...

随机推荐

  1. Math.round、Math.floor、Math.ceil 区别

    1.Math.round() 按照四舍五入的方式返回值 例如:Math.round(9.5)=10    Math.round(9.4)=9 2.Math.floor()返回最小整数 例如:Math. ...

  2. 一些学习比较好的网站,及es6学习好网站,前端用的相关库,及知道的插件

    图形可视化:d3js  echarts https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects ...

  3. Oracle 通过子查询批量添加、修改表数据

    1.通过查询快速创建表 create table test1(id,job,mgr,sal) as () ) ---这是一个分页查询 ok,表创建成功 2.通过查询快速创建视图 create or r ...

  4. 如何在Firebug中修改js变量的值

    在做项目的时候,经常需要调试js,要是项目环境在本地,可以直接在js代码里面设置断点或者修改变量值.但是在测试或者生产等线上环境时,再频繁登录服务器去修改js代码就显得麻烦了.项目线上环境,可以在fi ...

  5. vue打包后运行在本地/非服务器端环境的访问路径

    vue打包前的配置: 项目目录下--> config文件夹---> index.js: build:  { assetsPublickPath:  './',   // 设置成相对路径   ...

  6. java中多线程中测试某个条件的变化用 if 还是用 while?

    最近在研究wait和notify方法,发现有个地方要注意,但是网上又说得不是很明白的地方,就是经典的生产者和消费模式,使用wait和notify实现,判断list是否为空的这个为什么要用while而不 ...

  7. [转]Oracle中没有 if exists(...)

    本文转自:http://blog.csdn.net/hollboy/article/details/7550171 对于Oracle中没有 if exists(...) 的语法,目前有许多种解决方法, ...

  8. Exists 和 Not Exists

    只注重子查询是否有返回行,如有返回结果为真,否则为假,并不适用子查询的结果,仅用于测试子查询是否有返回结果. 语法: if exists (子查询) begin 语句块 end 例子: if exis ...

  9. RabbitMQ - exchange

    总结一下几种ExchangeTypes. 之前写发布/订阅模式时第一次提到了exchange type.即producer不是将消息直接放到队列中,而是先到exchange中,exchange主要用于 ...

  10. 05.部分类 partial

    namespace _06.部分类 { class Program { static void Main(string[] args) { } } /// <summary> /// 这个 ...