《使用Gin框架构建分布式应用》阅读笔记:p127-p142

《用Gin框架构建分布式应用》学习第9天,p127-p142总结,总计16页。

一、技术总结

1.Authentication方式汇总

(1)API keys

API keys 认证方式示例:

复制代码
func (handler *RecipesHandler) NewRecipeHandler(c *gin.Context) {
	// API-keys 认证
	value := os.Getenv("X-API-KEY")
	log.Println("X-API-KEY in env: ", value)
	if value == "" {
		value = "codists"
	}

	log.Println("X-API-KEY in header:", c.GetHeader("X-API-KEY"))
	if c.GetHeader("X-API-KEY") != value {
		c.JSON(http.StatusUnauthorized, gin.H{"message": "Unauthorized"})
		return
	}
	// 请求参数反序列化
	var recipe models.Recipe
	if err := c.ShouldBindJSON(&recipe); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
	}
	insertionResult, err := handler.collection.InsertOne(handler.ctx, &models.Recipe{})
	if err != nil {
		// 新增失败,返回错误给前端
		c.JSON(http.StatusInternalServerError, gin.H{"message": "新增失败" + err.Error()})
		return
	}

	log.Println("Remove recipes from Redis")
	handler.redisClient.Del(handler.ctx, "recipes")
	// 新增成功,返回 ID
	c.JSON(http.StatusOK, insertionResult.InsertedID)
}

这种方式在本人实际的工作经历中还没有遇到,不过在其它网站中有看到过实际应用。

(2)Basic Auth

(3)Client session

(4)OpenID Connect

(5)OpenAutherization(OAuth) 2.0

2.JWT

关于JWT的介绍可参考RFC7519:https://datatracker.ietf.org/doc/html/rfc7519。书中作者使用的是jwt-go这个包,现在这个包已经archived了,大家转而使用golang-jwt。

3.Gin知识点

(1)router.Group()

二、英语总结

1.pick up

p133,API keys are simple; however, anyone who makes a request to an API transmits their key,and in theory, the key can be picked up easily with a man-in-the-middle (MITM) attack

when no encryption is in use.

vt. to get sth。pick up这个词用法很灵活,感觉在很多场景能使用。

2.depict

p134, A JWT token consists of three parts separated by dots, as depicted in the following

screenshot...

(1)depict: de-("down") + pingere("to paint")。vt. to represent or show sth in a picture(描绘).

三、其它

虽然在使用 Python、Flask的时候使用过 JWT,但是本章阅读起来速度还是比较慢,本质在于对Go语言不熟悉,以及Go开发中使用的框架不熟悉。

四、参考资料

1. 编程

(1) Mohamed Labouardy,《Building Distributed Applications in Gin》:https://book.douban.com/subject/35610349

2. 英语

(1) Etymology Dictionary:https://www.etymonline.com

(2) Cambridge Dictionary:https://dictionary.cambridge.org

欢迎搜索及关注:编程人(a_codists)

相关推荐
福大大架构师每日一题2 小时前
ollama v0.30.7 正式发布:Hermes 桌面端落地,接口、文档、底层依赖全方位优化
golang·log4j
不爱编程的小陈4 小时前
深入解析 Go 网络 I/O 的底层引擎:从 epoll 到 netpoll
服务器·网络·golang
何以解忧,唯有..8 小时前
Go 语言数据类型详解:从基础到复合类型
开发语言·golang·mfc
踏着七彩祥云的小丑8 小时前
Go学习第7天:Map集合 + 递归函数 + 类型转换
开发语言·学习·golang·go
何以解忧,唯有..8 小时前
Go语言变量的声明方式详解
开发语言·后端·golang
寂夜了无痕8 小时前
Go 多版本管理工具G 保姆级安装配置教程
golang·go多版本管理
张忠琳9 小时前
【Go 1.26.4】Golang Slice 深度解析
开发语言·后端·golang
张忠琳1 天前
【Go 1.26.4】Golang Channel 深度解析
开发语言·后端·golang
张忠琳1 天前
【Go 1.26.4】Golang Map 深度解析
开发语言·后端·golang
何以解忧,唯有..1 天前
Go 语言安装与环境配置完整指南
开发语言·后端·golang