通用包
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
utils/meta/v1/user.go

76 lines
1.7 KiB

package meta
import (
"context"
"encoding/json"
"errors"
"github.com/go-kratos/kratos/v2/metadata"
)
const (
userMetaKey = "x-md-global-user"
)
var UserErr = errors.New("userinfo error")
// User 用户信息
type User struct {
// 用户id
Id int32 `json:"id"`
// 邮箱
Email string `json:"email"`
// 账号
Username string `json:"username"`
// 手机号
Phone string `json:"phone"`
// 昵称
Nickname string `json:"nickname"`
// 头像
Avatar string `json:"avatar"`
// 状态 1=正常;2=封禁
Status int32 `json:"status"`
}
// SetUserMetaClient 设置用户meta信息
func SetUserMetaClient(ctx context.Context, user *User) context.Context {
userInfo, _ := json.Marshal(user)
return metadata.AppendToClientContext(ctx, userMetaKey, string(userInfo))
}
// GetUserMetaClient 获取用户meta信息
func GetUserMetaClient(ctx context.Context) (*User, error) {
if meta, ok := metadata.FromClientContext(ctx); ok {
user := &User{}
if json.Unmarshal([]byte(meta.Get(userMetaKey)), user) != nil {
return nil, UserErr
}
return user, nil
}
return nil, UserErr
}
// SetUserMetaServer 设置用户meta信息
func SetUserMetaServer(ctx context.Context, user *User) context.Context {
userInfo, _ := json.Marshal(user)
var meta metadata.Metadata
var ok bool
if meta, ok = metadata.FromServerContext(ctx); ok {
meta.Set(userMetaKey, string(userInfo))
}
return metadata.NewServerContext(ctx, meta)
}
// GetUserMetaServer 获取用户meta信息
func GetUserMetaServer(ctx context.Context) (*User, error) {
if meta, ok := metadata.FromServerContext(ctx); ok {
user := &User{}
if json.Unmarshal([]byte(meta.Get(userMetaKey)), user) != nil {
return nil, UserErr
}
return user, nil
}
return nil, UserErr
}