- 浏览: 2551984 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
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(2)REST API with Gin
Install Gin
>go get github.com/gin-gonic/gin
Install govendor
>go get github.com/kardianos/govendor
Add current path to go path
export GOPATH="/Users/carl/work/easy/easygo:/Users/carl/work/sillycat/monitor-water/restful_go_api"
Create the directory
>mkdir -p src/com/sillycat/restful_go_api
go to that working directory
>cd /Users/carl/work/sillycat/monitor-water/restful_go_api/src/com/sillycat/restful_go_api
I am using Mac Pro, install with brew
>brew install govendor
Check the version
>govendor --version
v1.0.9
Init the Project
>govendor init
Fetch gin
>govendor fetch github.com/gin-gonic/gin@v1.2
Copy the latest sample here
>curl https://raw.githubusercontent.com/gin-gonic/gin/master/examples/basic/main.go > main.go
Run the sample
>go run main.go
Build that like this
>go install com/sillycat/restful_go_api
Run it like this
>bin/restful_go_api
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env:export GIN_MODE=release
- using code:gin.SetMode(gin.ReleaseMode)
[GIN-debug] GET /ping --> main.setupRouter.func1 (3 handlers)
[GIN-debug] GET /user/:name --> main.setupRouter.func2 (3 handlers)
[GIN-debug] POST /admin --> main.setupRouter.func3 (4 handlers)
I reactor the structure a little, code is in project monitor-water/restful_go_api
Read me is as follow:
#restful_go_api
Prepare the library
>go get github.com/gin-gonic/gin
How to Build
>go install 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 Run
>bin/restful_go_api
How to Test
>go test sillycat.com/restful_go_api
restful_go_api/src/sillycat.com/main.go
package main
import "github.com/gin-gonic/gin"
import "sillycat.com/restful_go_api/waterrecord"
var DB = make(map[string]string)
func SetupRouter() *gin.Engine {
// Disable Console Color
// gin.DisableConsoleColor()
router := gin.Default()
// Ping test
router.GET("/ping", func(c *gin.Context) {
c.String(200, "pong")
})
v1 := router.Group("api/v1")
{
v1.GET("/waterrecords", waterrecord.GetWaterRecords)
v1.GET("/waterrecords/:id", waterrecord.GetWaterRecord)
v1.POST("/waterrecords", waterrecord.PostWaterRecord)
v1.PUT("/waterrecords/:id", waterrecord.UpdateWaterRecord)
v1.DELETE("/waterrecords/:id", waterrecord.DeleteWaterRecord)
}
return router
}
func main() {
router := SetupRouter()
// Listen and Server in 0.0.0.0:8080
router.Run(":8080")
}
restful_go_api/src/sillycat.com/restful_go_api/waterrecord/waterrecord.go
package waterrecord
import (
"github.com/gin-gonic/gin"
)
func GetWaterRecords(c *gin.Context) {
c.JSON(200, gin.H{"ok": "GET api/v1/waterrecords"})
}
func GetWaterRecord(c *gin.Context) {
c.JSON(200, gin.H{"ok": "GET api/v1/waterrecords/1"})
}
func PostWaterRecord(c *gin.Context) {
c.JSON(200, gin.H{"ok": "POST api/v1/waterrecords"})
}
func UpdateWaterRecord(c *gin.Context) {
c.JSON(200, gin.H{"ok": "PUT api/v1/waterrecords/1"})
}
func DeleteWaterRecord(c *gin.Context) {
c.JSON(200, gin.H{"ok": "DELETE api/v1/waterrecords/1"})
}
restful_go_api/src/sillycat.com/restful_go_api/main_test.go
package main
import (
"bytes"
"github.com/gin-gonic/gin"
"net/http"
"net/http/httptest"
"testing"
)
func TestGetInstruction(t *testing.T) {
gin.SetMode(gin.TestMode)
testRouter := SetupRouter()
req, err := http.NewRequest("GET", "/api/v1/waterrecords/1", nil)
if err != nil {
t.Errorf("Get hearteat failed with error %d.", err)
}
resp := httptest.NewRecorder()
testRouter.ServeHTTP(resp, req)
if resp.Code != 200 {
t.Errorf("/api/v1/waterrecords failed with error code %d.", resp.Code)
}
}
func TestGetInstructions(t *testing.T) {
gin.SetMode(gin.TestMode)
testRouter := SetupRouter()
req, err := http.NewRequest("GET", "/api/v1/waterrecords", nil)
if err != nil {
t.Errorf("Get hearteat failed with error %d.", err)
}
resp := httptest.NewRecorder()
testRouter.ServeHTTP(resp, req)
if resp.Code != 200 {
t.Errorf("/api/v1/waterrecords failed with error code %d.", resp.Code)
}
}
func TestPostInstruction(t *testing.T) {
gin.SetMode(gin.TestMode)
testRouter := SetupRouter()
body := bytes.NewBuffer([]byte("{\"event_status\": \"83\", \"event_name\": \"100\"}"))
req, err := http.NewRequest("POST", "/api/v1/waterrecords", body)
req.Header.Set("Content-Type", "application/json")
if err != nil {
t.Errorf("Post hearteat failed with error %d.", err)
}
resp := httptest.NewRecorder()
testRouter.ServeHTTP(resp, req)
if resp.Code != 201 {
t.Errorf("/api/v1/waterrecords failed with error code %d.", resp.Code)
}
}
func TestPutInstruction(t *testing.T) {
gin.SetMode(gin.TestMode)
testRouter := SetupRouter()
body := bytes.NewBuffer([]byte("{\"event_status\": \"83\", \"event_name\": \"100\"}"))
req, err := http.NewRequest("PUT", "/api/v1/waterrecords/1", body)
req.Header.Set("Content-Type", "application/json")
if err != nil {
t.Errorf("Put hearteat failed with error %d.", err)
}
resp := httptest.NewRecorder()
testRouter.ServeHTTP(resp, req)
if resp.Code != 200 {
t.Errorf("/api/v1/waterrecords failed with error code %d.", resp.Code)
}
}
Database Layer
https://github.com/go-gorp/gorp
http://hao.jobbole.com/gorp/
https://awesome-go.com/#orm
https://github.com/go-xorm/xorm
http://xorm.io/
I will check and use xorm to see if it works.
References:
https://github.com/gin-gonic/gin
https://github.com/avelino/awesome-go#web-frameworks
https://github.com/kardianos/govendor
http://himarsh.org/build-restful-api-microservice-with-go/
https://github.com/marshallshen/instructions
https://coolshell.cn/articles/8460.html
https://coolshell.cn/articles/8489.html
https://stackoverflow.com/questions/30885098/go-local-import-in-non-local-package
Install Gin
>go get github.com/gin-gonic/gin
Install govendor
>go get github.com/kardianos/govendor
Add current path to go path
export GOPATH="/Users/carl/work/easy/easygo:/Users/carl/work/sillycat/monitor-water/restful_go_api"
Create the directory
>mkdir -p src/com/sillycat/restful_go_api
go to that working directory
>cd /Users/carl/work/sillycat/monitor-water/restful_go_api/src/com/sillycat/restful_go_api
I am using Mac Pro, install with brew
>brew install govendor
Check the version
>govendor --version
v1.0.9
Init the Project
>govendor init
Fetch gin
>govendor fetch github.com/gin-gonic/gin@v1.2
Copy the latest sample here
>curl https://raw.githubusercontent.com/gin-gonic/gin/master/examples/basic/main.go > main.go
Run the sample
>go run main.go
Build that like this
>go install com/sillycat/restful_go_api
Run it like this
>bin/restful_go_api
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env:export GIN_MODE=release
- using code:gin.SetMode(gin.ReleaseMode)
[GIN-debug] GET /ping --> main.setupRouter.func1 (3 handlers)
[GIN-debug] GET /user/:name --> main.setupRouter.func2 (3 handlers)
[GIN-debug] POST /admin --> main.setupRouter.func3 (4 handlers)
I reactor the structure a little, code is in project monitor-water/restful_go_api
Read me is as follow:
#restful_go_api
Prepare the library
>go get github.com/gin-gonic/gin
How to Build
>go install 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 Run
>bin/restful_go_api
How to Test
>go test sillycat.com/restful_go_api
restful_go_api/src/sillycat.com/main.go
package main
import "github.com/gin-gonic/gin"
import "sillycat.com/restful_go_api/waterrecord"
var DB = make(map[string]string)
func SetupRouter() *gin.Engine {
// Disable Console Color
// gin.DisableConsoleColor()
router := gin.Default()
// Ping test
router.GET("/ping", func(c *gin.Context) {
c.String(200, "pong")
})
v1 := router.Group("api/v1")
{
v1.GET("/waterrecords", waterrecord.GetWaterRecords)
v1.GET("/waterrecords/:id", waterrecord.GetWaterRecord)
v1.POST("/waterrecords", waterrecord.PostWaterRecord)
v1.PUT("/waterrecords/:id", waterrecord.UpdateWaterRecord)
v1.DELETE("/waterrecords/:id", waterrecord.DeleteWaterRecord)
}
return router
}
func main() {
router := SetupRouter()
// Listen and Server in 0.0.0.0:8080
router.Run(":8080")
}
restful_go_api/src/sillycat.com/restful_go_api/waterrecord/waterrecord.go
package waterrecord
import (
"github.com/gin-gonic/gin"
)
func GetWaterRecords(c *gin.Context) {
c.JSON(200, gin.H{"ok": "GET api/v1/waterrecords"})
}
func GetWaterRecord(c *gin.Context) {
c.JSON(200, gin.H{"ok": "GET api/v1/waterrecords/1"})
}
func PostWaterRecord(c *gin.Context) {
c.JSON(200, gin.H{"ok": "POST api/v1/waterrecords"})
}
func UpdateWaterRecord(c *gin.Context) {
c.JSON(200, gin.H{"ok": "PUT api/v1/waterrecords/1"})
}
func DeleteWaterRecord(c *gin.Context) {
c.JSON(200, gin.H{"ok": "DELETE api/v1/waterrecords/1"})
}
restful_go_api/src/sillycat.com/restful_go_api/main_test.go
package main
import (
"bytes"
"github.com/gin-gonic/gin"
"net/http"
"net/http/httptest"
"testing"
)
func TestGetInstruction(t *testing.T) {
gin.SetMode(gin.TestMode)
testRouter := SetupRouter()
req, err := http.NewRequest("GET", "/api/v1/waterrecords/1", nil)
if err != nil {
t.Errorf("Get hearteat failed with error %d.", err)
}
resp := httptest.NewRecorder()
testRouter.ServeHTTP(resp, req)
if resp.Code != 200 {
t.Errorf("/api/v1/waterrecords failed with error code %d.", resp.Code)
}
}
func TestGetInstructions(t *testing.T) {
gin.SetMode(gin.TestMode)
testRouter := SetupRouter()
req, err := http.NewRequest("GET", "/api/v1/waterrecords", nil)
if err != nil {
t.Errorf("Get hearteat failed with error %d.", err)
}
resp := httptest.NewRecorder()
testRouter.ServeHTTP(resp, req)
if resp.Code != 200 {
t.Errorf("/api/v1/waterrecords failed with error code %d.", resp.Code)
}
}
func TestPostInstruction(t *testing.T) {
gin.SetMode(gin.TestMode)
testRouter := SetupRouter()
body := bytes.NewBuffer([]byte("{\"event_status\": \"83\", \"event_name\": \"100\"}"))
req, err := http.NewRequest("POST", "/api/v1/waterrecords", body)
req.Header.Set("Content-Type", "application/json")
if err != nil {
t.Errorf("Post hearteat failed with error %d.", err)
}
resp := httptest.NewRecorder()
testRouter.ServeHTTP(resp, req)
if resp.Code != 201 {
t.Errorf("/api/v1/waterrecords failed with error code %d.", resp.Code)
}
}
func TestPutInstruction(t *testing.T) {
gin.SetMode(gin.TestMode)
testRouter := SetupRouter()
body := bytes.NewBuffer([]byte("{\"event_status\": \"83\", \"event_name\": \"100\"}"))
req, err := http.NewRequest("PUT", "/api/v1/waterrecords/1", body)
req.Header.Set("Content-Type", "application/json")
if err != nil {
t.Errorf("Put hearteat failed with error %d.", err)
}
resp := httptest.NewRecorder()
testRouter.ServeHTTP(resp, req)
if resp.Code != 200 {
t.Errorf("/api/v1/waterrecords failed with error code %d.", resp.Code)
}
}
Database Layer
https://github.com/go-gorp/gorp
http://hao.jobbole.com/gorp/
https://awesome-go.com/#orm
https://github.com/go-xorm/xorm
http://xorm.io/
I will check and use xorm to see if it works.
References:
https://github.com/gin-gonic/gin
https://github.com/avelino/awesome-go#web-frameworks
https://github.com/kardianos/govendor
http://himarsh.org/build-restful-api-microservice-with-go/
https://github.com/marshallshen/instructions
https://coolshell.cn/articles/8460.html
https://coolshell.cn/articles/8489.html
https://stackoverflow.com/questions/30885098/go-local-import-in-non-local-package
发表评论
-
Stop Update Here
2020-04-28 09:00 316I will stop update here, and mo ... -
NodeJS12 and Zlib
2020-04-01 07:44 476NodeJS12 and Zlib It works as ... -
Docker Swarm 2020(2)Docker Swarm and Portainer
2020-03-31 23:18 369Docker Swarm 2020(2)Docker Swar ... -
Docker Swarm 2020(1)Simply Install and Use Swarm
2020-03-31 07:58 370Docker Swarm 2020(1)Simply Inst ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 337Traefik 2020(1)Introduction and ... -
Portainer 2020(4)Deploy Nginx and Others
2020-03-20 12:06 431Portainer 2020(4)Deploy Nginx a ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 436Private Registry 2020(1)No auth ... -
Docker Compose 2020(1)Installation and Basic
2020-03-15 08:10 374Docker Compose 2020(1)Installat ... -
VPN Server 2020(2)Docker on CentOS in Ubuntu
2020-03-02 08:04 455VPN Server 2020(2)Docker on Cen ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 385Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 478NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 423Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 337Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 248GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 451GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 328GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 314Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 319Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 294Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 312Serverless with NodeJS and Tenc ...
相关推荐
【Golang Gin RESTFul API with SQLite】是一个项目,它教你如何使用Go语言的Gin框架来构建符合RESTful架构的API,并结合SQLite数据库进行数据存储。在这个项目中,我们将探讨Gin框架的核心特性,RESTful API设计...
golang——使用 Golang 和 Gin 开发 RESTful API
用于golang的Camunda REST API客户端安装 go get github.com/citilinkru/camunda-client-go/v2用法创建客户端: client := camunda_client_go . NewClient (camunda_client_go. ClientOptions {EndpointUrl : ...
这将极大地提升你在Golang Web开发中的技能和效率,无论是创建RESTful API、构建Web应用还是搭建后台服务,Gin都是一个值得信赖的工具。在实践中不断探索这些源码,你将更好地掌握Gin框架的精髓。
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开发的高效、简洁且并发性能出色的编程语言,其官方提供...
Gin+Gorm开发Golang API快速开发脚手架 Singo Singo: Simple Single Golang Web Service go-crud正式改名为Singo! 使用Singo开发Web服务: 用最简单的架构,实现够用的框架,服务海量用户 ... Singo文档 ...
golang-stats-api-handler, Golang cpu,内存,gc等信息api处理程序 golang-stats-api-handlerGolang cpu,内存,gc等信息api处理程序。 安装go get github.com/fukata/golang-stats-api-handler示
4. **路由设计**:根据REST原则设计API路由,如GET /users, POST /users, PUT /users/:id等。 5. **测试**:编写单元测试和集成测试,确保每个功能的正确性。 6. **日志记录**:使用如`logrus`或`zap`库进行日志...
在本文中,我们将深入探讨如何使用Gin、Gorm、JWT和Casbin这四个关键组件构建一个基于Golang的RBAC(Role-Based Access Control)权限管理系统。Gin是一个高效的Web框架,Gorm是一个用于Go语言的ORM库,JWT(Json ...
在本文中,我们将深入探讨如何使用Golang和MySQL构建一个简单的REST API。Golang,也称为Go语言,是由Google开发的一种静态类型、编译型、并发型、垃圾回收的编程语言,特别适合于构建高性能的网络服务。而MySQL是...
Golang REST API示例 :rocket: :man::laptop: 完整列出已使用的内容: -Web框架数据库/ sql的扩展。 -Go的PostgreSQL驱动程序和工具包使用fangs进行配置 -Golang的类型安全Redis客户端记录器-结构和现场验证 -JSON ...
本文将深入探讨"Go-httpexpect-golang的端到端HTTP和REST API"这一主题,介绍如何利用httpexpect库进行高效的测试。 httpexpect是Go语言中一个强大的工具,专为编写端到端HTTP和REST API测试而设计。它提供了简洁、...
2. **Gin框架**:Gin是Golang的一个Web开发框架,它使用MVC(模型-视图-控制器)模式,提供了一套快速开发API和Web应用的结构。Gin依赖于martini中间件库,通过简洁的语法和高效性能,使开发者能够快速构建强大的Web...
RocketAPI是用Golang语言开发的一个针对Rocketchat平台的REST API客户端库。Rocketchat是一款流行的开源聊天和协作工具,提供了丰富的API接口供开发者进行集成和扩展。使用RocketAPI,开发者可以方便地在Go应用中与...
本文档介绍了一本名为《golang_gin_restful_api.pdf》的小册子,该小册详细介绍了使用Go语言和Gin框架构建RESTful API服务的过程。Gin是一个高性能的Go(golang)语言编写的Web框架,专门用于API服务的构建,它提供...
用于Go的现代,简单,快速且自以为是的REST API框架,包括电池。 发音为IPA: 。 该项目的目标是提供: 适用于Go开发人员的现代REST API后端框架由和描述对中间件,JSON / CBOR和其他功能的一流支持护栏防止常见错误...