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. RabbitMQ---初识

    1.概述 1.1 RabbitMQ   是  实现了   高级消息队列协议(AMQP) 的开源   消息代理软件,也称为  面向消息的中间件: AMQP:Advanced Message Queuin ...

  2. jQuery练习 | 复选框及编辑模式

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&quo ...

  3. ant.design初探

    第一部分: 前言 推荐网站: https://ant.design/docs/spec/introduce-cn ant.design是基于react开发的一个解放ui和前端的工具,它提供了一致的设计 ...

  4. 安装多个PHP环境会导致phpinfo和php -v中查看到的PHP版本不一致

    以前在上一个公司用的是集成环境wamp,PHP版本是5.5.后面换了一个公司,项目用的是PHP版本是5.2.今天想打开以前的项目想优化一下,发现pdo_mysql.dll扩展无法加载,于是想看看是不是 ...

  5. Bootstrap使用模态框modal实现表单提交弹出框

    Bootstrap 模态框(Modal)插件 模态框(Modal)是覆盖在父窗体上的子窗体.通常,目的是显示来自一个单独的源的内容,可以在不离开父窗体的情况下有一些互动.子窗体可提供信息.交互等.如果 ...

  6. <数据挖掘导论>读书笔记4--其他分类技术

    1.基于规则的分类器 2.最近邻分类器 3.贝叶斯分类器 4.人工神经网络 5.支持向量机 6.组合方法 7.不平衡类问题 8.多类问题

  7. 【vm安装vmtools】

    使用sudo ./安装命令 对vmware-tools-distrib文件夹里面vmware-install.pl文件夹进行安装 sudo ./vmware-install.pl

  8. CXF - JAX-WS入门

    相关dependency,我使用的版本是2.7.11: <dependency> <groupId>org.apache.cxf</groupId> <art ...

  9. .NET的EF框架中:在应用程序配置文件中找不到名为“”的连接字符串问题

    今天在使用EF Code First框架时,当把模型都定义好了,想通过程序包管理控制台利用enable-migrations –force来生成数据库表的时候报错了,如下: 找不到连接字符串,但是我仔 ...

  10. 前端标注软件-pxcook像素大厨使用心得

    我们在日常开发过程中,设计师给提供的UI图,经常需要标注尺寸,有时候设计师难免会遗漏标注,这样就会大大的增加我们的沟通成本,因此,使用一款好用的标注软件就尤为重要,我推荐这款标注软件---pxcook ...