Go實戰--經過gin-gonic框架搭建restful api服務(github.com/gin-gonic/gin)

生命不止,繼續 go go go !!!mysql

先插播一條廣告,給你堅持學習golang的理由:
《2017 軟件開發薪酬調查:Go 和 Scala 是最賺錢的語言》 git


言歸正傳!github

以前寫過使用golang實現簡單的restful api相關的博客:
Go實戰–實現簡單的restful api(The way to go)golang

其中,使用了github.com/gorilla/mux,今天要跟你們介紹的是gin-gonic/gin。web

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.sql

github地址:
https://github.com/gin-gonic/gin數據庫

獲取:json

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

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/212未完待續: 組織代碼結構--------------------- 做者:一蓑煙雨1989 來源:CSDN 原文:https://blog.csdn.net/wangshubo1989/article/details/76906605 版權聲明:本文爲博主原創文章,轉載請附上博文連接!

相關文章
相關標籤/搜索