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 ...
随机推荐
- 漫谈TCPIP协议原理
一.每次说道TCPIP协议,有能说会道者,总爱说三次握手,什么意思? 顾名思义,假设有两个机器A和B 1.当A发送给B一个包的时候,B接收到了,这个时候,B有两个选择,要么将包数据放入缓存,等待处理, ...
- WinScp结合Putty在Windows与UNIX之间进行文件传输
1. 关于传输协议: SSH Secure Shell安全外壳协议 SFTP Secure File Transfer Protocal安全文件传送协议 2. WinScp与Putty的作用: Put ...
- vue-router学习
JS push goTo(){ , postId: ' }}) } router.js // 动态路径参数 以冒号开头 { path: '/user/:id', component: User } { ...
- 新建IP核为灰色并显示there is no project open
问题: ise显示there is no project open. “You may browse the IP Catalog but you will not be able to genera ...
- SQLite3开发接口函数详解
SQLite3是SQLite一个全新的版本,它虽然是在SQLite 2.8.13的代码基础之上开发的,但是使用了和之前的版本不兼容的数据库格式和API. SQLite3是为了满足以下的需求而开发的: ...
- Win7/Vista/Server2008下VS 环境 调试调用 HTTP.SYS 无法启动监听服务及启动后其他机器无法访问端口
一. VS调试在Win7(vista系列)操作系统下 HttpListener无法绑定多个 指定IP.端口问题 来自:http://www.cnblogs.com/ryhan/p/4195693.ht ...
- LinuxShell脚本编程基础2-变量与数值运算、父shell和子shell
1.变量和数值运算 Shell脚本的变量不需要声明的 对变量赋值有两种方式, 直接用“=” 或者用键盘输入值 #!/bin/bash name1="Jack" echo $name ...
- STM32F407 使用HAL库延时微妙实现方法(附CubeMX配置过程)
STM32F407 使用HAL库延时微妙实现方法(STM32CubeMX配置) 作者 : 李剀出处 : https://www.cnblogs.com/kevin-nancy/p/10696681.h ...
- 在windows服务器上设置301、伪静态(wordpress)
新建一个httpd.ini文件,插入代码: [ISAPI_Rewrite] RewriteCond Host: ^wuchao\.cc$ RewriteRule (.*) http\://www\.w ...
- 前端渲染模板(一):Thymeleaf
一.使用 本篇文章将以SpringBoot为框架来介绍Thymeleaf的用法. 1 资源文件的约定目录结构 Maven的资源文件目录:/src/java/resources spring-boot ...