go 网站访问添加浏览器自带的登录功能(网站加密访问)

642人浏览 2022-10-21

goLang 网站访问添加浏览器自带的登录功能(网站加密访问)

效果图:

开始实现(本文使用的gin框架,其他同理)

1.router路由添加中间件

//登录限制
r.Use(middleware.HTTPAuthMiddleware())
	

2.设置中间件

//HTTPAuthMiddleware login middleware
func HTTPAuthMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		//这里用户名密码应该是动态设置的
		user := "admin"
		passwd := "123123"
		reqUser, reqPasswd, hasAuth := ctx.Request.BasicAuth()
		if (user == "" && passwd == "") ||
			(hasAuth && reqUser == user && reqPasswd == passwd) {
			ctx.Next()
		} else {
			ctx.Writer.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
			http.Error(ctx.Writer, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
            ctx.Abort()
		}

	}
}

3.重新编译程序运行。

 

 

 

 

 

推荐文章

GORM 自定义结构体关联的数据库表名称和自定义结构体字段对应的数据表字段名
2021-02-23
KChatRoom在线多人聊天室,项目是使用Websocket和Gin框架基于Golang开发的在线聊天室
2021-05-17
Gin框架下获取所有路由信息
2021-07-14
搜索文章