生命不止,继续 go go go !!!

先插播一条广告,给你坚持学习golang的理由:
《2017 软件开发薪酬调查:Go 和 Scala 是最赚钱的语言》

言归正传!

之前写过使用golang实现简单的restful api相关的博客:
Go实战–实现简单的restful api(The way to go)

其中,使用了github.com/gorilla/mux,今天要跟大家介绍的是gin-gonic/gin。

gin-gonic/gin
介绍:
Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance – up to 40 times faster. If you need smashing performance, get yourself some Gin.

github地址:
https://github.com/gin-gonic/gin

获取:

go get github.com/gin-gonic/gin
1
例子:

package main

import "github.com/gin-gonic/gin"

func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
运行:

[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.main.func1 (3 handlers)
[GIN-debug] Environment variable PORT is undefined. Using port :8080 by default
[GIN-debug] Listening and serving HTTP on :8080
1
2
3
4
5
6
7
8
通过浏览器访问:
http://localhost:8080/ping

// 20170808110257
// http://localhost:8080/ping

{
"message": "pong"
}
1
2
3
4
5
6
全局设置环境:

gin.SetMode(gin.DebugMode)
1

gin.SetMode(gin.ReleaseMode)
1
获得路由实例:

r := gin.Default()
1
构建restful api

创建五个routes:

package main

import (
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
v1 := router.Group("/api/v1/userinfo")
{
v1.POST("/", CreateUser)
v1.GET("/", FetchAllUsers)
v1.GET("/:id", FetchSingleUser)
v1.PUT("/:id", UpdateUser)
v1.DELETE("/:id", DeleteUser)
}
router.Run()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
下面我们要使用gin+mysql构建restful api。
如果对于golang中的MySQL不够熟悉的话,可以看看我之前写过的博文:
Go实战–go语言操作MySQL数据库(go-sql-driver/mysql)

先实现一个简单的根据id来FetchSingleUser吧:
我们事先通过命令行创建了user_info表以及一行数据,id=2, name=wangshubo

开始golang程序:
定义结构体:

type Person struct {
Id int
Name string
}
1
2
3
4
check函数:

func checkErr(err error) {
if err != nil {
panic(err)
}
}
1
2
3
4
5
FetchSingleUser方法:
我们要返回json, gin对json也进行了封装,所以不再需要我们提供类似encoding/json之类的package。

func FetchSingleUser(c *gin.Context) {

id := c.Param("id")

db, err := sql.Open("mysql", "root:wangshubo@/test?charset=utf8")
checkErr(err)

defer db.Close()

err = db.Ping()
checkErr(err)

var (
person Person
result gin.H
)
row := db.QueryRow("select id, name from user_info where id = ?;", id)
err = row.Scan(&person.Id, &person.Name)
if err != nil {
// If no results send null
result = gin.H{
"result": nil,
"count": 0,
}
} else {
result = gin.H{
"result": person,
"count": 1,
}
}
c.JSON(http.StatusOK, result)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
浏览器访问:
http://localhost:8080/api/v1/userinfo/1

// 20170808141904
// http://localhost:8080/api/v1/userinfo/1

{
"count": 0,
"result": null
}
1
2
3
4
5
6
7
浏览器访问:
http://localhost:8080/api/v1/userinfo/2

// 20170808141940
// http://localhost:8080/api/v1/userinfo/2

{
"count": 1,
"result": {
"Id": 2,
"Name": "wangshubo"
}
}
1
2
3
4
5
6
7
8
9
10
gin输出log:

[GIN] 2017/08/08 - 14:19:03 | 200 | 16.0127ms | ::1 | GET /api/v1/userinfo/1
[GIN] 2017/08/08 - 14:19:39 | 200 | 56.0381ms | ::1 | GET /api/v1/userinfo/2
1
2
未完待续:
组织代码结构
---------------------
作者:一蓑烟雨1989
来源:CSDN
原文:https://blog.csdn.net/wangshubo1989/article/details/76906605
版权声明:本文为博主原创文章,转载请附上博文链接!

Go实战--通过gin-gonic框架搭建restful api服务(github.com/gin-gonic/gin)的更多相关文章

  1. 基于gin web框架搭建RESTful API服务

    这篇主要学习go项目中的项目结构.项目规范等知识,ROM采用的database/sql的写法. 1.技术框架 利用的是ginweb框架,然后ROM层选用database/sql,安装mysql驱动.安 ...

  2. 使用CodeIgniter框架搭建RESTful API服务

    使用CodeIgniter框架搭建RESTful API服务 发表于 2014-07-12   |   分类于 翻译笔记   |   6条评论 在2011年8月的时候,我写了一篇博客<使用Cod ...

  3. 基于Gin+Gorm框架搭建MVC模式的Go语言后端系统

    文/朱季谦 环境准备:安装Gin与Gorm 本文搭建准备环境:Gin+Gorm+MySql. Gin是Go语言的一套WEB框架,在学习一种陌生语言的陌生框架,最好的方式,就是用我们熟悉的思维去学.作为 ...

  4. 使用 Beego 搭建 Restful API 项目

    1 环境准备 首先你需要在你的环境安装以下软件: go:编程语言运行环境 git:版本控制工具 beego:go 语言流行的开发框架 bee:beego 配套的快速搭建工具 你喜欢的数据库:这里以 M ...

  5. 【PHP】基于ThinkPHP框架搭建OAuth2.0服务

    [PHP]基于ThinkPHP框架搭建OAuth2.0服务 http://leyteris.iteye.com/blog/1483403

  6. 【重学Node.js 第1&2篇】本地搭建Node环境并起RESTful Api服务

    本地搭建Node环境并起RESTful Api服务 课程介绍看这里:https://www.cnblogs.com/zhangran/p/11963616.html 项目github地址:https: ...

  7. 开放接口/RESTful/Api服务的设计和安全方案

    总体思路 这个涉及到两个方面问题:一个是接口访问认证问题,主要解决谁可以使用接口(用户登录验证.来路验证)一个是数据数据传输安全,主要解决接口数据被监听(HTTPS安全传输.敏感内容加密.数字签名) ...

  8. 玩转 SpringBoot 2 快速搭建 | RESTful Api 篇

    概述 RESTful 是一种架构风格,任何符合 RESTful 风格的架构,我们都可以称之为 RESTful 架构.我们常说的 RESTful Api 是符合 RESTful 原则和约束的 HTTP ...

  9. 搭建RESTful API 之 实现WSGI服务的URL映射

    javarestfull 搭建参考 http://blog.csdn.net/hejias/article/details/47424511 问题引出:对于一个稍具规模的网站来说,实现的功能不可能通过 ...

随机推荐

  1. server中intersect的用法

    intersect 就像数学中的交集一样, select nam from  tb_table1 intersect select name from  tb_table2  查询的是两个数据集的交集 ...

  2. [UOJ#274][清华集训2016]温暖会指引我们前行

    [UOJ#274][清华集训2016]温暖会指引我们前行 试题描述 寒冬又一次肆虐了北国大地 无情的北风穿透了人们御寒的衣物 可怜虫们在冬夜中发出无助的哀嚎 “冻死宝宝了!” 这时 远处的天边出现了一 ...

  3. [NOIP2002] 提高组 洛谷P1033 自由落体

    题目描述 在高为 H 的天花板上有 n 个小球,体积不计,位置分别为 0,1,2,….n-1.在地面上有一个小车(长为 L,高为 K,距原点距离为 S1).已知小球下落距离计算公式为 d=1/2*g* ...

  4. [NOIP1999] 普及组

    回文数 /*By SilverN*/ #include<algorithm> #include<iostream> #include<cstring> #inclu ...

  5. [USACO08OPEN]牛的车Cow Cars

    题目描述 N (1 <= N <= 50,000) cows conveniently numbered 1..N are driving in separate cars along a ...

  6. C# 获得图片的分辨率和大小

    double DPI = pictureBox1.Image.HorizontalResolution;//获得分辨率 gisoracle double w = 1.0 * pictureBox1.I ...

  7. Could not find leader nimbus

    运行storm ui, 然后访问storm ui 的网页的时候,死活跑不起来.后面,根据下面这篇文章的说法, 停止zookeeper 之后,删掉zookeeper 上面的storm 节点, 然后再重启 ...

  8. 猫猫学iOS 之微博项目实战(2)微博主框架-自己定义导航控制器NavigationController

    猫猫分享,必须精品 原创文章,欢迎转载.转载请注明:翟乃玉的博客 地址:http://blog.csdn.net/u013357243?viewmode=contents 一:加入导航控制器 上一篇博 ...

  9. angular react vue 浏览器兼容情况汇总

    一.逻辑层 框架 (1)angular Angular早在1.3版本就抛弃了对ie8的支持. (2)react React 早在0.14.x 版本就抛弃了对ie8的支持. (3)vue Vue就没打算 ...

  10. 【Java 虚拟机探索之路系列】:JIT编译器

    作者:郭嘉 邮箱:allenwells@163.com 博客:http://blog.csdn.net/allenwells github:https://github.com/AllenWell 为 ...