1 Star 0 Fork 0

brucewang / go公共库

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
grpc_header.go 883 Bytes
一键复制 编辑 原始数据 按行查看 历史
brucewang 提交于 2022-01-05 08:08 . 公共库初始化
package utils
import (
"context"
"github.com/google/uuid"
"google.golang.org/grpc/metadata"
)
const (
// RequestIDKey requestID key
RequestIDKey = "x-request-id"
// UsernameKey username key
UsernameKey = "x-username"
)
// GetRequestID request id from header
func GetRequestID(ctx context.Context) string {
id := GetHeaderFirst(ctx, RequestIDKey)
if id == "" {
id = NewRequestID()
}
return id
}
// GetUsername get username from header
func GetUsername(ctx context.Context) string {
return GetHeaderFirst(ctx, UsernameKey)
}
// GetHeaderFirst get header first value
func GetHeaderFirst(ctx context.Context, key string) string {
if md, ok := metadata.FromIncomingContext(ctx); ok {
if values := md.Get(key); len(values) > 0 {
return values[0]
}
}
return ""
}
// NewRequestID generate a RequestId
func NewRequestID() string {
return uuid.New().String()
}
Go
1
https://gitee.com/brucewangzhihua1/go-public-library.git
git@gitee.com:brucewangzhihua1/go-public-library.git
brucewangzhihua1
go-public-library
go公共库
v1.0.1

搜索帮助