1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
bind.go 2.03 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2024-01-09 17:26 . bind header
package api
import (
"gitee.com/h79/goutils/auth/token"
"gitee.com/h79/goutils/common/result"
"gitee.com/h79/goutils/common/stringutil"
"strings"
)
const (
Head = "HEADER"
Token = "TOKEN"
Uid = "UID"
)
type HeadOption func(ctx Context, header *Header)
func BindHead(ctx Context, option HeadOption) {
header := NewHeader(ReqHead{})
header.ReadFrom(ctx)
if option != nil {
option(ctx, header)
}
header.ClientIP = ctx.HttpContext().ClientIP()
ctx.CacheContext().Set(Head, header)
}
func WithHeadOption(ctx Context, header *Header) {
if header.Version == "" {
header.Version = ctx.HttpContext().Query(CVersion)
}
if header.Source == "" {
header.Source = ctx.HttpContext().Query(CSource)
}
if header.SeqId == "" {
header.SeqId = ctx.HttpContext().Query(CSeqId)
}
if header.ReqAt == 0 {
header.ReqAt = stringutil.StringToInt64(ctx.HttpContext().Query(CTimeAt))
}
if header.App.AppId == "" {
header.App.AppId = ctx.HttpContext().Query(CAppId)
}
if header.App.Terminal == "" {
header.App.Terminal = ctx.HttpContext().Query(CTerminal)
}
if header.App.Version == "" {
header.App.Version = header.Version
}
if header.App.Source == "" {
header.App.Source = header.Source
}
}
const kToken = "token"
func GetTokenSource(ctx Context) token.Source {
base := GetBase(ctx)
return token.Source{AppId: base.App.AppId, Source: base.App.Source}
}
func TokenReq(ctx Context) (string, error) {
return GetToken(ctx, CToken)
}
func GetToken(ctx Context, keys ...string) (string, error) {
var tok = ""
var header = ctx.HeaderContext()
for i := range keys {
tok = header.Get(keys[i])
if len(tok) > 6 {
if strings.ToUpper(tok[0:7]) == "BEARER " {
return tok[7:], nil
}
return tok, nil
}
}
tok = header.Get(kToken)
if len(tok) > 0 {
return tok, nil
}
tok = ctx.HttpContext().Query(kToken)
if len(tok) > 0 {
return tok, nil
}
return "", result.RErrAuth
}
func Bearer(tok string) string {
if len(tok) <= 0 {
return ""
}
if strings.ToUpper(tok[0:7]) == "BEARER " {
return tok
}
return "Bearer " + tok
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.22.6

搜索帮助