- 浏览: 2542962 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
2018 Golang Update(3)REST API with ORM
Database Layer
https://github.com/go-xorm/xorm
http://xorm.io/
MySQL Driver
https://github.com/go-sql-driver/mysql
Library
>go get github.com/go-xorm/xorm
>go get github.com/go-sql-driver/mysql
I find most of the CURD methods in here
https://github.com/go-xorm/xorm
Here is how to init the DB connection in restful_go_api/src/sillycat.com/waterrecord/db.go
package waterrecord
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/go-xorm/core"
"github.com/go-xorm/xorm"
)
func initDatabase() *xorm.Engine {
var engine *xorm.Engine
var err error
engine, err = xorm.NewEngine("mysql", "watermonitor:xxxxxxx@tcp(sillycat.ddns.net:3306)/watermonitor?charset=utf8")
if err != nil {
fmt.Println(err)
}
engine.Ping() //ping
engine.ShowSQL(true) //show SQL
engine.Logger().SetLevel(core.LOG_DEBUG)
return engine
}
Method and mapping in restful_go_api/sillycat.com/restful_go_api/waterrecord/waterrecord.go
package waterrecord
import (
"github.com/gin-gonic/gin"
"log"
"strconv"
"time"
)
type WaterRecord struct {
Id int64
Location string `xorm:"location varchar(256) not null"`
StartTime string `xorm:"start_time varchar(256) not null"`
EndTime string `xorm:"end_time varchar(256) not null"`
Duration int `xorm:"duration int(11)"`
ReleaseDate string `xorm:"release_date varchar(256)"`
CreateDate time.Time `xorm:"create_date DATETIME "`
UpdateDate time.Time `xorm:"update_date DATETIME"`
}
var engine = initDatabase()
func (waterRecord WaterRecord) TableName() string {
return "water_monitor"
}
func GetWaterRecords(c *gin.Context) {
var items []WaterRecord
query := "SELECT id, location, start_time, end_time, duration, release_date, create_date, update_date FROM water_monitor"
err := engine.Sql(query).Find(&items)
if err != nil {
log.Fatal("Get err when exec query: ", err)
}
log.Println("query result: ", items)
c.JSON(200, items)
}
func GetWaterRecord(c *gin.Context) {
var item WaterRecord
id := c.Param("id")
has, err := engine.Where("id = ?", id).Get(&item)
if err != nil {
log.Fatal("Get one item err: ", err)
}
if has {
c.JSON(200, item)
} else {
c.JSON(404, gin.H{"error": "WaterRecord not found"})
}
}
func PostWaterRecord(c *gin.Context) {
var item WaterRecord
c.Bind(&item)
if item.Location != "" && item.ReleaseDate != "" {
_, err := engine.Insert(&item)
if err != nil {
log.Fatal("Insert fail:", err)
} else {
c.JSON(201, item)
}
} else {
c.JSON(422, gin.H{"error": "fields are empty!"})
}
}
func UpdateWaterRecord(c *gin.Context) {
var item WaterRecord
id := c.Param("id")
c.Bind(&item)
has, err := engine.SQL("select * from water_monitor where id = ?", id).Exist()
if err != nil {
log.Fatal("Fail to find item:", err)
} else {
if has {
item.Id, _ = strconv.ParseInt(id, 0, 64)
_, err := engine.Id(id).Update(&item)
if err != nil {
log.Fatal("Fail to update item:", err)
} else {
c.JSON(200, item)
}
} else {
c.JSON(404, gin.H{"error": "Water Record not found"})
}
}
}
func DeleteWaterRecord(c *gin.Context) {
id := c.Param("id")
item := new(WaterRecord)
has, err := engine.SQL("select * from water_monitor where id = ?", id).Exist()
if err != nil {
log.Fatal("Fail to find item:", err)
} else {
if has {
//itemID, _ := strconv.ParseInt(id, 0, 64)
_, err := engine.Where("id = ?", id).Delete(item)
if err != nil {
log.Fatal("Fail to delete:", err)
} else {
c.JSON(202, gin.H{"id": id})
}
} else {
c.JSON(404, gin.H{"error": "Water Record not found"})
}
}
}
It works great on local MAC and remote CentOS and RaspberryPi
#restful_go_api
Prepare the library
>go get github.com/gin-gonic/gin
>go get github.com/go-xorm/xorm
>go get github.com/go-sql-driver/mysql
How to Build for local
>go install sillycat.com/restful_go_api
How to Run Test
>go test sillycat.com/restful_go_api
How to Build for Linux
>env GOOS=linux GOARCH=amd64 go build -o bin/restful_go_api_linux -v sillycat.com/restful_go_api
How to Build for Raspberrypi
>env GOOS=linux GOARCH=arm GOARM=7 go build -o bin/restful_go_api_arm -v sillycat.com/restful_go_api
How to Run
>bin/restful_go_api
Maybe Later, I can change the layer to Model, Dao, Controller like Java, haha.
References:
http://sillycat.iteye.com/admin/blogs/2411149
http://solee.me/2016/10/26/golang-ginyu-xormjian-dan-shi-jian/
build for RaspberryPi
https://www.thepolyglotdeveloper.com/2017/04/cross-compiling-golang-applications-raspberry-pi/
Database Layer
https://github.com/go-xorm/xorm
http://xorm.io/
MySQL Driver
https://github.com/go-sql-driver/mysql
Library
>go get github.com/go-xorm/xorm
>go get github.com/go-sql-driver/mysql
I find most of the CURD methods in here
https://github.com/go-xorm/xorm
Here is how to init the DB connection in restful_go_api/src/sillycat.com/waterrecord/db.go
package waterrecord
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/go-xorm/core"
"github.com/go-xorm/xorm"
)
func initDatabase() *xorm.Engine {
var engine *xorm.Engine
var err error
engine, err = xorm.NewEngine("mysql", "watermonitor:xxxxxxx@tcp(sillycat.ddns.net:3306)/watermonitor?charset=utf8")
if err != nil {
fmt.Println(err)
}
engine.Ping() //ping
engine.ShowSQL(true) //show SQL
engine.Logger().SetLevel(core.LOG_DEBUG)
return engine
}
Method and mapping in restful_go_api/sillycat.com/restful_go_api/waterrecord/waterrecord.go
package waterrecord
import (
"github.com/gin-gonic/gin"
"log"
"strconv"
"time"
)
type WaterRecord struct {
Id int64
Location string `xorm:"location varchar(256) not null"`
StartTime string `xorm:"start_time varchar(256) not null"`
EndTime string `xorm:"end_time varchar(256) not null"`
Duration int `xorm:"duration int(11)"`
ReleaseDate string `xorm:"release_date varchar(256)"`
CreateDate time.Time `xorm:"create_date DATETIME "`
UpdateDate time.Time `xorm:"update_date DATETIME"`
}
var engine = initDatabase()
func (waterRecord WaterRecord) TableName() string {
return "water_monitor"
}
func GetWaterRecords(c *gin.Context) {
var items []WaterRecord
query := "SELECT id, location, start_time, end_time, duration, release_date, create_date, update_date FROM water_monitor"
err := engine.Sql(query).Find(&items)
if err != nil {
log.Fatal("Get err when exec query: ", err)
}
log.Println("query result: ", items)
c.JSON(200, items)
}
func GetWaterRecord(c *gin.Context) {
var item WaterRecord
id := c.Param("id")
has, err := engine.Where("id = ?", id).Get(&item)
if err != nil {
log.Fatal("Get one item err: ", err)
}
if has {
c.JSON(200, item)
} else {
c.JSON(404, gin.H{"error": "WaterRecord not found"})
}
}
func PostWaterRecord(c *gin.Context) {
var item WaterRecord
c.Bind(&item)
if item.Location != "" && item.ReleaseDate != "" {
_, err := engine.Insert(&item)
if err != nil {
log.Fatal("Insert fail:", err)
} else {
c.JSON(201, item)
}
} else {
c.JSON(422, gin.H{"error": "fields are empty!"})
}
}
func UpdateWaterRecord(c *gin.Context) {
var item WaterRecord
id := c.Param("id")
c.Bind(&item)
has, err := engine.SQL("select * from water_monitor where id = ?", id).Exist()
if err != nil {
log.Fatal("Fail to find item:", err)
} else {
if has {
item.Id, _ = strconv.ParseInt(id, 0, 64)
_, err := engine.Id(id).Update(&item)
if err != nil {
log.Fatal("Fail to update item:", err)
} else {
c.JSON(200, item)
}
} else {
c.JSON(404, gin.H{"error": "Water Record not found"})
}
}
}
func DeleteWaterRecord(c *gin.Context) {
id := c.Param("id")
item := new(WaterRecord)
has, err := engine.SQL("select * from water_monitor where id = ?", id).Exist()
if err != nil {
log.Fatal("Fail to find item:", err)
} else {
if has {
//itemID, _ := strconv.ParseInt(id, 0, 64)
_, err := engine.Where("id = ?", id).Delete(item)
if err != nil {
log.Fatal("Fail to delete:", err)
} else {
c.JSON(202, gin.H{"id": id})
}
} else {
c.JSON(404, gin.H{"error": "Water Record not found"})
}
}
}
It works great on local MAC and remote CentOS and RaspberryPi
#restful_go_api
Prepare the library
>go get github.com/gin-gonic/gin
>go get github.com/go-xorm/xorm
>go get github.com/go-sql-driver/mysql
How to Build for local
>go install sillycat.com/restful_go_api
How to Run Test
>go test sillycat.com/restful_go_api
How to Build for Linux
>env GOOS=linux GOARCH=amd64 go build -o bin/restful_go_api_linux -v sillycat.com/restful_go_api
How to Build for Raspberrypi
>env GOOS=linux GOARCH=arm GOARM=7 go build -o bin/restful_go_api_arm -v sillycat.com/restful_go_api
How to Run
>bin/restful_go_api
Maybe Later, I can change the layer to Model, Dao, Controller like Java, haha.
References:
http://sillycat.iteye.com/admin/blogs/2411149
http://solee.me/2016/10/26/golang-ginyu-xormjian-dan-shi-jian/
build for RaspberryPi
https://www.thepolyglotdeveloper.com/2017/04/cross-compiling-golang-applications-raspberry-pi/
发表评论
-
Stop Update Here
2020-04-28 09:00 310I will stop update here, and mo ... -
NodeJS12 and Zlib
2020-04-01 07:44 468NodeJS12 and Zlib It works as ... -
Docker Swarm 2020(2)Docker Swarm and Portainer
2020-03-31 23:18 362Docker Swarm 2020(2)Docker Swar ... -
Docker Swarm 2020(1)Simply Install and Use Swarm
2020-03-31 07:58 364Docker Swarm 2020(1)Simply Inst ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 330Traefik 2020(1)Introduction and ... -
Portainer 2020(4)Deploy Nginx and Others
2020-03-20 12:06 424Portainer 2020(4)Deploy Nginx a ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 428Private Registry 2020(1)No auth ... -
Docker Compose 2020(1)Installation and Basic
2020-03-15 08:10 367Docker Compose 2020(1)Installat ... -
VPN Server 2020(2)Docker on CentOS in Ubuntu
2020-03-02 08:04 445VPN Server 2020(2)Docker on Cen ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 377Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 468NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 414Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 332Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 243GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 445GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 321GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 307Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 310Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 286Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 303Serverless with NodeJS and Tenc ...
相关推荐
用于golang的Camunda REST API客户端安装 go get github.com/citilinkru/camunda-client-go/v2用法创建客户端: client := camunda_client_go . NewClient (camunda_client_go. ClientOptions {EndpointUrl : ...
【Golang Gin RESTFul API with SQLite】是一个项目,它教你如何使用Go语言的Gin框架来构建符合RESTful架构的API,并结合SQLite数据库进行数据存储。在这个项目中,我们将探讨Gin框架的核心特性,RESTful API设计...
Golang中文API,由热心网友翻译上传
Golang REST API入门 此入门工具供您选择并根据需要进行修改。 这个项目促进思想上的代码。 并且,如果有任何零件的设计模式不正确,希望您通过提出一个问题来提供反馈。 这是什么? 这个想法是使所有项目(包括...
Golang-Rest-API 示例Golang Rest API 命令 # Start server make run # Start server for local make run-local # Stop server make stop
go-wordpress, Golang API的客户端库( Wordpress REST API ) go-wp-apiGolang api的客户端库( Wordpress REST API )安装go get github.com/sogko/go-wordpress用法快速示例package main
《Golang中文API详解》 在编程领域,API(Application Programming Interface)是开发者与软件库、框架或操作系统交互的关键工具。对于Go语言,一个由Google开发的高效、简洁且并发性能出色的编程语言,其官方提供...
golang-stats-api-handler, Golang cpu,内存,gc等信息api处理程序 golang-stats-api-handlerGolang cpu,内存,gc等信息api处理程序。 安装go get github.com/fukata/golang-stats-api-handler示
Golang REST API示例 :rocket: :man::laptop: 完整列出已使用的内容: -Web框架数据库/ sql的扩展。 -Go的PostgreSQL驱动程序和工具包使用fangs进行配置 -Golang的类型安全Redis客户端记录器-结构和现场验证 -JSON ...
在本文中,我们将深入探讨如何使用Golang和MySQL构建一个简单的REST API。Golang,也称为Go语言,是由Google开发的一种静态类型、编译型、并发型、垃圾回收的编程语言,特别适合于构建高性能的网络服务。而MySQL是...
用于Go的现代,简单,快速且自以为是的REST API框架,包括电池。 发音为IPA: 。 该项目的目标是提供: 适用于Go开发人员的现代REST API后端框架由和描述对中间件,JSON / CBOR和其他功能的一流支持护栏防止常见错误...
3. **模型操作**:Go-Toyorm提供了丰富的API,如`Create`、`Find`、`Update`、`Delete`,用于执行常见的数据库操作。例如,使用`db.NewOrm().Insert(&user)`即可插入一个新的用户记录。 ### 二、Go-Toyorm主要特性 ...
本文将深入探讨"Go-httpexpect-golang的端到端HTTP和REST API"这一主题,介绍如何利用httpexpect库进行高效的测试。 httpexpect是Go语言中一个强大的工具,专为编写端到端HTTP和REST API测试而设计。它提供了简洁、...
Go-queryset 是一个专为Golang设计的100%类型安全的ORM(对象关系映射)框架。ORM允许开发者使用面向对象的方式来操作数据库,而不是直接编写SQL语句,极大地提高了开发效率和代码可读性。在这个框架中,类型安全是...
RocketAPI是用Golang语言开发的一个针对Rocketchat平台的REST API客户端库。Rocketchat是一款流行的开源聊天和协作工具,提供了丰富的API接口供开发者进行集成和扩展。使用RocketAPI,开发者可以方便地在Go应用中与...
ezorm是用于golang的基于代码生成的ORM库,支持mongodb / sql服务器/ mysql / redis。 ezorm ezorm是用于golang的基于代码生成的ORM库,支持mongodb / sql服务器/ mysql / redis。 数据模型是使用YAML文件定义的,...
在本文中,我们将深入探讨如何使用Golang与DeepL API进行交互,特别是在无需TOKEN的情况下实现免费的翻译功能。首先,让我们了解一下Golang和DeepL API的基础知识。 Golang(Go语言)是由Google开发的一种静态类型...
Golang示例样板 特征 清除代码(DDD) 杜松子酒框架 Docker和docker-compose ORM与gorm 使用Kafka的发布/订阅 整合测试 与github action集成 怎么跑 有两种方式可以运行此应用程序,带docker或不带docker # ...
在Go(Golang)开发中,使用RESTful API已经成为构建现代Web服务的标准实践。REST(Representational State Transfer)架构风格提供了简洁、可扩展的方式,使得客户端和服务器之间的交互变得高效。"Go-gopencils" 是...
gofight, 在Golang中,测试API处理程序编写 Gofight 面向 Golang Web框架的API处理程序测试。支持框架HTTP处理程序 Golang包HTTP提供HTTP客户端和服务器实现。Echo 支持 v3.0.0多路复用器HttpRo