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 ...
随机推荐
- 在ionic3自定义组件中使用官方组件
先创建组件: ionic g component xxx 在components里面如下图引入
- Ubuntu14.04下编译安装或apt-get方式安装搭建Apache或Httpd服务(图文详解)
不多说,直接上干货! 写在前面的话 对于 在Ubuntu系统上,编译安装Apache它默认路径是在/usr/local/apache2/htdocs 或者编译安装httpd它默认路径是在/usr/lo ...
- 登陆界面背景动画的css样式
为了达到更好的用户体验,登陆界面需要设计多张背景图进行动态切换 <!doctype html> <html lang="en"> <head> ...
- js中有关类、对象的增强函数
javascript中继承的实现 基础实现 function Range(from,to){ this.from =from; this.to =to; } Range.prototype = { i ...
- ES6学习准备
ES6学习准备 选择运行环境 ES6的语法,nodeJs.浏览器不一定都支持,不同版本的支持情况不一样.在学习过程中,如何确定是自己写的代码有问题,还是运行环境不支持呢? 首先,浏览器端一般支持的特性 ...
- JS字符串与二进制的转化
JS字符串与二进制的相互转化 1 2 3 4 5 //字符串转ascii码,用charCodeAt(); //ascii码转字符串,用fromCharCode(); var str = "A ...
- 在ASPNETCORE中获得所有Action
在ASPNETCORE中获得所有Action 本文旨在记录自己在aspnetcore工作中需要获取所有Action,在查询了资料后进行了几种方法的记录.后期有发现其它方式再进行追加. 一.通过 反射 ...
- 如何优雅的封装一个DOM事件库
1.DOM0级事件和DOM2级事件 DOM 0级事件是元素内的一个私有属性:div.onclick = function () {},对一个私有属性赋值(在该事件上绑定一个方法).由此可知DOM 0级 ...
- OAuth2.0 微信授权机制
我在了解设计Restful接口的时候,发现涉及到接口验证,可以利用OAuth2.0机制来验证. 我开发的微信端Web网页通过微信授权的时候,微信端也是用OAuth2.0机制来获取用户基本信息. OAu ...
- master.sys.sysprocesses相关内容
sysprocesses 表中保存关于运行在 Microsoft® SQL Server™ 上的进程的信息.这些进程可以是客户端进程或系统进程. sysprocesses 只存储在 master 数据 ...