https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/middlewares.go

中间件定义

package users

import (
"net/http"
"strings" "github.com/dgrijalva/jwt-go/request"
"github.com/gin-gonic/gin"
"github.com/wangzitian0/golang-gin-starter-kit/common"
) // 请求头 认证参数前缀标注TOKEN处理, 不使用默认的Bearer标注,而是用TOKEN
// 函数 返回TOKEN字符串值
func stripBearerPrefixFromTokenString(tok string) (string, error) {
if len(tok) > 5 && strings.ToUpper(tok[0:6]) == "TOKEN " {
return tok[6:], nil
}
return tok, nil
} // 从请求头获取 Authorization 参数内容
var AuthorizationHeaderExtractor = &request.PostExtractionFilter{
request.HeaderExtractor{"Authorization"},
stripBearerPrefixFromTokenString,
} // 从AuthorizationHeaderExtractor获取 access_token 参数内容
var MyAuth2Extractor = &request.MultiExtractor{
AuthorizationHeaderExtractor,
request.ArgumentExtractor{"access_token"},
} // 函数 更新用户上下文相关内容
func UpdateContextUserModel(c *gin.Context, my_user_id uint) {
var myUserModel UserModel
if my_user_id != 0 {
db := common.GetDB()
db.First(&myUserModel, my_user_id)
}
c.Set("my_user_id", my_user_id)
c.Set("my_user_model", myUserModel)
} // 函数 用户自定义的中间件, 使用 r.Use(AuthMiddleware(true))
func AuthMiddleware(auto401 bool) gin.HandlerFunc {
return func(c *gin.Context) {
// 初始化用户上下文,用户ID初值为0, 用户初值为nil
UpdateContextUserModel(c, 0) // 获取请求中的token内容,并解密为token对象
token, err := request.ParseFromRequest(c.Request, MyAuth2Extractor, func(token *jwt.Token) (interface{}, error) {
b := ([]byte(common.NBSecretPassword))
return b, nil
}) if err != nil {
// 中间件开关为true时,返回认证错误信息
if auto401 {
c.AbortWithError(http.StatusUnauthorized, err)
}
return
} // 成功获取payload信息并且校验成功,调用函数更新用户上下文
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
my_user_id := uint(claims["id"].(float64))
//fmt.Println(my_user_id, claims["id"])
UpdateContextUserModel(c, my_user_id)
}
}
}

从golang-gin-realworld-example-app项目学写httpapi (五)的更多相关文章

  1. 从golang-gin-realworld-example-app项目学写httpapi (八)

    https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/common/unit_test.go 单元测试 ...

  2. 从golang-gin-realworld-example-app项目学写httpapi (七)

    https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/hello.go main调用 package ...

  3. 从golang-gin-realworld-example-app项目学写httpapi (六)

    https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/validators.go 验证器 ...

  4. 从golang-gin-realworld-example-app项目学写httpapi (四)

    https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/routers.go 路由定义 pa ...

  5. 从golang-gin-realworld-example-app项目学写httpapi (三)

    https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/serializers.go 序列化 ...

  6. 从golang-gin-realworld-example-app项目学写httpapi (二)

    https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/models.go 模型定义 use ...

  7. 从golang-gin-realworld-example-app项目学写httpapi (一)

    https://wangzitian0.github.io/2013/06/29/zero-to-one-1/ https://github.com/gothinkster/golang-gin-re ...

  8. Golang Gin 项目包依赖管理 godep 使用

    Golang Gin 项目包依赖管理 godep 使用 标签(空格分隔): Go 在按照github.com/tools/godep文档go get完包以后,调整项目结构为$GOPATH/src/$P ...

  9. Golang Gin 项目使用 Swagger

    Golang Gin 项目使用 Swagger 标签(空格分隔): Go 首先需要github.com/swaggo/gin-swagger和github.com/swaggo/gin-swagger ...

随机推荐

  1. C 标准库 - string.h之memcmp使用

    memcmp Compare two blocks of memory. Compares the first num bytes of the block of memory pointed by ...

  2. Leetcode 337. House Robber III

    337. House Robber III Total Accepted: 18475 Total Submissions: 47725 Difficulty: Medium The thief ha ...

  3. linux下perforce(p4)的使用方法和命令

    环境变量: export P4PASSWD=abcdefg export P4CLIENT=dyoldfish.com export P4USER=dyoldfish export P4PORT=19 ...

  4. SQL常用性能相关脚本

    --调试语句性能前记得清空执行计划 每次执行需优化SQL前,带上清除缓存的设置SQL. 平常在进行SQL Server性能优化时,为了确保真实还原性能问题,我们需要关闭SQL Server自身的执行计 ...

  5. Windows下安装PHP开发环境

    一.Apache 因为Apache官网只提供源代码,如果要使用必须得自己编译,这里我选择第三方安装包Apache Lounge. 进入Apachelounge官方下载地址:http://www.apa ...

  6. XRP共识算法

    目录 共识协议属性 账本历史 信任的验证 共识协议属性 XRP Ledger使用的共识协议不同于之前的任何区块链.该协议称为XRP Ledger共识协议,旨在具有以下重要属性: 使用XRP Ledge ...

  7. java并发编程(10)Fork/Join

    Fork/Join JAVA7中出现的Fork/Join,类似于分布式文件系统hadoop的mapreduce思想,就是将任务分割,再分割,直到分割到满足条件 为了便于理解:编程逻辑可以借用 递归的思 ...

  8. vuex源码分析3.0.1(原创)

    前言 chapter1 store构造函数 1.constructor 2.get state和set state 3.commit 4.dispatch 5.subscribe和subscribeA ...

  9. [转]C#进阶系列——WebApi 接口返回值不困惑:返回值类型详解

    本文转自:http://www.cnblogs.com/landeanfen/p/5501487.html 阅读目录 一.void无返回值 二.IHttpActionResult 1.Json(T c ...

  10. 【C#高级】泛型(一)

    泛型,.net 2.0之后出现,基本只要代码中出现 ‘<>’ 尖括号就可以确定是泛型. 在2.0之前大多是使用Object来代替,因为所有类都是Object的派生类,根据继承的原理Obje ...