go使用Gin web框架开发api入门
2023-07-09 本文已影响0人
护念
gin框架是go语言用于开发web的框架,开发一个api,仍然包含路由、控制器、数据处理、响应返回这么几部分。
1.项目准备
初始化项目
mkdir web-server-gin
cd web-server-gin
go mod init example/web-server-gin # 初始化模块
touch main.go # 作为入口文件,为简单起见,所有请求和处理都放在这里
main.go 文件内容
// main.go
package main
import(
"net/http"
"github.com/gin-gonic/gin" // 引入我们要的用的gin框架
)
func main() {
}
2. 开始我们第一个api
这里我们以唱片album需求来实现,遵从restful api原则,开发
GET /alubms
获取唱片列表
- 先写入路由
// main.go
package main
import(
"net/http"
"github.com/gin-gonic/gin" // 引入我们要的用的gin框架
)
// 此步骤添加
func main() {
router := gin.Default()
router.GET("/albums", getAlbums) // 路由写在这里
router.Run("localhost:8080")
}
- 补全控制器
// main.go
package main
import(
"net/http"
"github.com/gin-gonic/gin" // 引入我们要的用的gin框架
)
// 此步骤添加
func main() {
router := gin.Default()
router.GET("/albums", getAlbums) // 路由写在这里
router.Run("localhost:8080")
}
// 控制器函数 gin.Context 是框架的上下问
func getAlbums(c *gin.Context) {
// c.IndentedJSON是返回缩减的json
c.IndentedJSON(http.StatusOK, albums)
}
// 结构体 ID(字段) String(字段类型)
type album struct {
ID string `json:"id"`
Title string `json:"title"`
Artist string `json:"artist"`
Price float64 `json:"price"`
}
// 用新的结构体类型 定义一个唱片集合
var albums = []album{
{ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
{ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
{ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}
- 运行
go mod tidy # 运行获取需要用到的依赖,为什么在最终这里执行,不在一开始引入模块的时候执行,目前的理解是,最终才会知道需要用到哪些依赖
go run . # 运行
在命令行curl http://localhost:8080/albums
dongmingyan@pro ⮀ ~/go_playground/web-server-gin ⮀ go run .
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
[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 /albums --> main.getAlbums (3 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Listening and serving HTTP on localhost:8080
[GIN] 2023/07/10 - 22:34:52 | 200 | 116.705µs | 127.0.0.1 | GET "/albums"
dongmingyan@pro ⮀ ~ ⮀ curl http://localhost:8080/albums
[
{
"id": "1",
"title": "Blue Train",
"artist": "John Coltrane",
"price": 56.99
},
{
"id": "2",
"title": "Jeru",
"artist": "Gerry Mulligan",
"price": 17.99
},
{
"id": "3",
"title": "Sarah Vaughan and Clifford Brown",
"artist": "Sarah Vaughan",
"price": 39.99
}
]%
2.添加接口 POST /albums
创建唱片
- 添加路由
// main.go
// main函数中添加
router.POST("/albums", postAlbums)
- 添加控制器,main.go文件底部添加
// main.go
// 添加条目到albums
func postAlbums(c *gin.Context) {
// 定义一个变量 为结构体类型album
var newAlbum album
// 调用 BindJSON 绑定接受到的json到 newAlbum变量
if err := c.BindJSON(&newAlbum); err != nil {
return
}
// 将newAlbum 加入到albums中,这里是加到内存中的
albums = append(albums, newAlbum)
c.IndentedJSON(http.StatusCreated, newAlbum)
}
- 运行,如果之前是运行的需要先终止掉,重新
go run .
dongmingyan@pro ⮀ ~ ⮀ curl http://localhost:8080/albums \
--include \
--header "Content-Type: application/json" \
--request "POST" \
--data '{"id": "4","title": "The Modern Sound of Betty Carter","artist": "Betty Carter","price": 49.99}'
HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8
Date: Tue, 11 Jul 2023 13:15:06 GMT
Content-Length: 116
{
"id": "4",
"title": "The Modern Sound of Betty Carter",
"artist": "Betty Carter",
"price": 49.99
}%
3. 添加GET /albums/:id
接口
- 在main函数中,添加路由
// main.go
router.GET("/albums/:id", getAlbumByID)
- 添加控制器函数
// main.go
func getAlbumByID(c *gin.Context) {
id := c.Param("id") // 路径参数获取值
// 循环找到id
for _, a := range albums {
if a.ID == id {
c.IndentedJSON(http.StatusOK, a)
return
}
}
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"})
}
- 运行,
go run .
✘ dongmingyan@pro ⮀ ~/go_playground/web-server-gin ⮀ go run .
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
[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 /albums --> main.getAlbums (3 handlers)
[GIN-debug] POST /albums --> main.postAlbums (3 handlers)
[GIN-debug] GET /albums/:id --> main.getAlbumByID (3 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Listening and serving HTTP on localhost:8080
[GIN] 2023/07/11 - 21:24:02 | 200 | 108.951µs | 127.0.0.1 | GET "/albums/3"
[GIN] 2023/07/11 - 21:24:05 | 200 | 74.037µs | 127.0.0.1 | GET "/albums/1"
dongmingyan@pro ⮀ ~ ⮀ curl http://localhost:8080/albums/1
{
"id": "1",
"title": "Blue Train",
"artist": "John Coltrane",
"price": 56.99
}%