系列文章目录
第一章 gin初步认识
第二章 设置API
第三章 使用MongoDB数据持久化
目录
注:
- 系列文章是对应上述英文原版书的学习笔记
- 相关自己的练习代码包含注释,放在在本人的gitee,欢迎star
- 所有内容允许转载,如果侵犯书籍的著作权益,请联系删除
- 笔记持续更新中
设置API
前言
本章将介绍如何构建RESTful API,
介绍HTTP的其他方法和路由(router)的方法。
还有如何编写OpenAPI和生成API文档。
gin框架的微服务应用架构

简单的说就是,微服务通过暴露RESTful API来管理http协议下的方法(recipes)
定义数据模型
type Recipe struct {
Name string `json:"name"` // 使用注解指定字段
Tags []string `json:"tags"`
Ingredients []string `json:"ingredients"`
Instructions []string `json:"instructions"`
PublishedAt time.Time `json:"PublishedAt"`
}
在数据模型后面加上注解,有助于Go和JSON在字段名
http结点方法

实现HTTP路由
1. 定义全局变量,用来存储数据
使用数据库后,就可以直接使用数据库返回的数据
var recipes []Recipe
func init() {
recipes = make([]recipes, 0)
}
2. 编写POST响应处理函数
func NewRecipeHandler(c *gin.Context) {
var recipe Recipe
// 从POST请求的正文中获取并绑定到数据实体
// c.ShouldBindJSON(&recipe)
if err := c.ShouldBindJSON(&recipe); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error()})
return
}
// 生成独一无二的ID代码
recipe.ID = xid.New().String()
recipe.PublishedAt = time.Now()
recipes = append(recipes, recipe)
// 把数据模型实体recipe返回为json模式
c.JSON(http.Status

本文档介绍了如何使用Go Gin框架构建微服务应用,包括定义数据模型、实现HTTP路由(POST、GET、PUT、DELETE方法)以及编写OpenAPI规范(OAS)来生成API文档。通过示例代码展示了如何处理HTTP请求,以及如何用Go Swagger自动生成和展示API说明。
最低0.47元/天 解锁文章
947

被折叠的 条评论
为什么被折叠?



