golang rest api example
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的更多相关文章
- Golang面向API编程-interface(接口)
Golang面向API编程-interface(接口) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. Golang并不是一种典型的面向对象编程(Object Oriented Pr ...
- golang esl api
通过ESL 调取FS的状态,比如show calls : 用golang eventsocket 实现 conn, err := eventsocket.Dial("192.168.5.3 ...
- golang restful api
https://medium.com/@petrousov/how-to-build-a-restful-api-in-go-for-phonebook-app-d55f7234a10 ------- ...
- Golang Gateway API 搭建教程
原文链接 随着微服务的兴起,行业里出现了非常多优秀的微服务网关框架,今天教大家搭建一套国人,用Golang写的微服务网关框架. 这里啰嗦一句,可能到今天还有人不理解什么是微服务,为什么要用微服务.目前 ...
- golang gin框架 使用swagger生成api文档
github地址:https://github.com/swaggo/gin-swagger 1.下载swag $ go get -u github.com/swaggo/swag/cmd/swag ...
- Golang下通过syscall调用win32的dll(calling Windows DLLs from Go )
很多同学比如我虽然很喜欢golang,但是还是需要调用很多遗留项目或者其他优秀的开源项目,这时怎么办呢?我们想到的方法是用package里的syscall结合cgo 注意此处有坑: 在我调试时显示no ...
- 在Golang中获取系统的磁盘空间内存占用
获取磁盘占用情况(Linux/Mac下有效) import ( "syscall" ) type DiskStatus struct { All uint64 `json:&quo ...
- golang包快速生成base64验证码
base64Captcha快速生成base64编码图片验证码字符串 支持多种样式,算术,数字,字母,混合模式,语音模式. Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一.Base6 ...
- golang web 方案
概要 开发 web 框架 数据库 认证 日志 配置 静态文件服务 上传/下载 发布 docker 打包 部署中遇到的问题 时区问题 概要 轻量的基于 golang 的 web 开发实践. golang ...
随机推荐
- ptyhon技能树及其学习资源
GUI编程 tkinter Github项目 Tkinter by example effbot 文档 tkinter的一个designer,可以像在qtdesign那样创建UI文件 pyqt5 py ...
- Django 配置访问静态文件
1.settings.py 首先在 settings 文件中,引用 os 模块: import os 定义根目录: BASE_DIR = os.path.dirname(os.path.dirna ...
- (转)CentOS7 LVM添加硬盘及扩容
原文:http://blog.51cto.com/qicheng0211/1620171 9818人阅读 一.LVM简介 LVM是 Logical Volume Manager(逻辑卷管理)的简写 ...
- Visual Studio 2013复制项目
在当前解决方案下复制项目的步骤: 1. 在硬盘存放代码的目录下将整个文件拷贝一份,修改文件夹名字,改成新的项目名称, 然后修改 *.csproj文件,名字必须与新项目名一致. 2. 在解决方案上右键 ...
- shell -- 获取绝对路径
readlink -f <file> readlink -m <file> 会把file的相对路径转化为绝对路径 几个选项的区别: -f, --canonicalize can ...
- Getting over the dangers of rm command in Linux---reference
reference:http://www.coolcoder.in/2014/01/getting-over-dangers-of-rm-command-in.html When we want to ...
- addEventListener()和removeEventListener()
作用: addEventListener()与removeEventListener()用于处理指定和删除事件处理程序操作. 它们都接受3个参数:事件名.事件处理的函数和布尔值. 布尔值参数是true ...
- UILable 标题加粗代码
UILable 标题加粗代码: 加粗; [UILabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:18]]; 加粗并 ...
- Java入门系列-25-NIO(实现非阻塞网络通信)
还记得之前介绍NIO时对比传统IO的一大特点吗?就是NIO是非阻塞式的,这篇文章带大家来看一下非阻塞的网络操作. 补充:以数组的形式使用缓冲区 package testnio; import java ...
- Go语言备忘录(3):net/http包的使用模式和源码解析
本文是晚辈对net/http包的一点浅显的理解,文中如有错误的地方请前辈们指出,以免误导! 转摘本文也请注明出处:Go语言备忘录(3):net/http包的使用模式和源码解析,多谢! 目录: 一.h ...