用户信息传到service
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/url"
|
||||
"strconv"
|
||||
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
type UserInfo struct {
|
||||
ID int64
|
||||
Name string
|
||||
RawUID string
|
||||
Refresh string
|
||||
Valid bool
|
||||
}
|
||||
|
||||
// GetUserFromCtx 从rpc metadata获取用户
|
||||
func GetUserFromCtx(ctx context.Context) UserInfo {
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
return UserInfo{Valid: false}
|
||||
}
|
||||
|
||||
uidList := md.Get("x-user-id")
|
||||
nameList := md.Get("x-user-name")
|
||||
refreshList := md.Get("x-refresh")
|
||||
|
||||
rawUID := ""
|
||||
encodeName := ""
|
||||
refresh := ""
|
||||
if len(uidList) > 0 {
|
||||
rawUID = uidList[0]
|
||||
}
|
||||
if len(nameList) > 0 {
|
||||
encodeName = nameList[0]
|
||||
}
|
||||
if len(refreshList) > 0 {
|
||||
refresh = refreshList[0]
|
||||
}
|
||||
|
||||
if rawUID == "" {
|
||||
return UserInfo{Valid: false}
|
||||
}
|
||||
|
||||
uid, err := strconv.ParseInt(rawUID, 10, 64)
|
||||
if err != nil {
|
||||
return UserInfo{
|
||||
RawUID: rawUID,
|
||||
Name: encodeName,
|
||||
Refresh: refresh,
|
||||
Valid: false,
|
||||
}
|
||||
}
|
||||
|
||||
// 解码中文
|
||||
userName, _ := url.QueryUnescape(encodeName)
|
||||
|
||||
return UserInfo{
|
||||
ID: uid,
|
||||
Name: userName,
|
||||
RawUID: rawUID,
|
||||
Refresh: refresh,
|
||||
Valid: true,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user