This commit is contained in:
zhaocy 2022-06-01 19:39:51 +08:00
parent aeb1a1ab4d
commit 42ca630ca9
13 changed files with 186 additions and 56 deletions

2
cmd/robot/robot.go Normal file
View File

@ -0,0 +1,2 @@
package robot

View File

@ -1,24 +1,20 @@
package comm package comm
import (
"github.com/liwei1dao/lego/core"
)
///内置错误码 0-1000 请外部应用服务不要占用 ///内置错误码 0-1000 请外部应用服务不要占用
const ( const (
ErrorCode_Success core.ErrorCode = 0 //成功 ErrorCode_Success int32 = 0 //成功
ErrorCode_NoFindService core.ErrorCode = 10 //没有找到远程服务器 ErrorCode_NoFindService int32 = 10 //没有找到远程服务器
ErrorCode_RpcFuncExecutionError core.ErrorCode = 11 //Rpc方法执行错误 ErrorCode_RpcFuncExecutionError int32 = 11 //Rpc方法执行错误
ErrorCode_CacheReadError core.ErrorCode = 12 //缓存读取失败 ErrorCode_CacheReadError int32 = 12 //缓存读取失败
ErrorCode_SqlExecutionError core.ErrorCode = 13 //数据库执行错误 ErrorCode_SqlExecutionError int32 = 13 //数据库执行错误
ErrorCode_ReqParameterError core.ErrorCode = 14 //请求参数错误 ErrorCode_ReqParameterError int32 = 14 //请求参数错误
ErrorCode_SignError core.ErrorCode = 15 //签名错误 ErrorCode_SignError int32 = 15 //签名错误
ErrorCode_InsufficientPermissions core.ErrorCode = 16 //权限不足 ErrorCode_InsufficientPermissions int32 = 16 //权限不足
ErrorCode_NoLogin core.ErrorCode = 17 //未登录 ErrorCode_NoLogin int32 = 17 //未登录
ErrorCode_UserSessionNobeing core.ErrorCode = 18 //用户不存在 ErrorCode_UserSessionNobeing int32 = 18 //用户不存在
) )
var ErrorCodeMsg = map[core.ErrorCode]string{ var ErrorCodeMsg = map[int32]string{
ErrorCode_Success: "成功", ErrorCode_Success: "成功",
ErrorCode_NoFindService: "没有找到远程服务器", ErrorCode_NoFindService: "没有找到远程服务器",
ErrorCode_RpcFuncExecutionError: "Rpc方法执行错误", ErrorCode_RpcFuncExecutionError: "Rpc方法执行错误",
@ -31,10 +27,10 @@ var ErrorCodeMsg = map[core.ErrorCode]string{
ErrorCode_UserSessionNobeing: "用户不存在", ErrorCode_UserSessionNobeing: "用户不存在",
} }
func GetErrorCodeMsg(code core.ErrorCode) string { func GetErrorCodeMsg(code int32) string {
if v, ok := ErrorCodeMsg[code]; ok { if v, ok := ErrorCodeMsg[code]; ok {
return v return v
} else { } else {
return core.GetErrorCodeMsg(code) return "未描述"
} }
} }

View File

@ -36,11 +36,11 @@ func Test_WebSocket(t *testing.T) {
}() }()
loginreq := &pb.UserLoginReq{ loginreq := &pb.UserLoginReq{
Name: "liwei", Name: "aaa",
} }
logindata, _ := proto.Marshal(loginreq) logindata, _ := proto.Marshal(loginreq)
message := &pb.UserMessage{ message := &pb.UserMessage{
ServiceMethod: "Login", ServiceMethod: "login.login",
Data: logindata, Data: logindata,
} }
data, _ := proto.Marshal(message) data, _ := proto.Marshal(message)

View File

@ -5,8 +5,11 @@ import (
"go_dreamfactory/comm" "go_dreamfactory/comm"
"go_dreamfactory/modules" "go_dreamfactory/modules"
"go_dreamfactory/pb" "go_dreamfactory/pb"
"go_dreamfactory/sys/cache"
"go_dreamfactory/sys/db"
"github.com/liwei1dao/lego/sys/log" "github.com/liwei1dao/lego/sys/log"
"go.mongodb.org/mongo-driver/mongo"
) )
type LoginComp struct { type LoginComp struct {
@ -14,8 +17,39 @@ type LoginComp struct {
} }
//登录 //登录
func (this *LoginComp) Login(ctx context.Context, session comm.IUserSession, rsp *pb.UserLoginReq) error { func (this *LoginComp) Login(ctx context.Context, session comm.IUserSession, req *pb.UserLoginReq) error {
log.Debugf("User - Login: session:%v rsp:%v", session.ToString(), rsp) log.Debugf("User - Login: session:%v rsp:%v", session.ToString(), req)
db_user, err := db.Defsys.FindUserByAccount(req.Name)
if err != nil {
if err != mongo.ErrNoDocuments {
return err
}
}
if db_user.UserId == 0 {
db_user.Account = req.Name
err = db.Defsys.CreateUser(db_user)
if err != nil {
return err
}
}
session.Build(db_user.UserId)
cache_user := &pb.Cache_UserData{
SessionId: session.GetSessionId(),
GatewayServiceId: session.GetGatewayServiceId(),
UserData: db_user,
}
err = cache.Defsys.UpdateUser(cache_user)
if err != nil {
return err
}
session.SendMsg("loginRsp", &pb.UserLoginResp{
Code: comm.ErrorCode_Success,
})
return nil return nil
} }

10
sys/cache/core.go vendored
View File

@ -10,14 +10,14 @@ type (
const () const ()
var defsys ISys var Defsys ISys
func OnInit(config map[string]interface{}, option ...Option) (err error) { func OnInit(config map[string]interface{}, option ...Option) (err error) {
var options Options var options Options
if options, err = newOptions(config, option...); err != nil { if options, err = newOptions(config, option...); err != nil {
return return
} }
defsys, err = newSys(options) Defsys, err = newSys(options)
return return
} }
@ -26,10 +26,8 @@ func NewSys(option ...Option) (sys ISys, err error) {
if options, err = newOptionsByOption(option...); err != nil { if options, err = newOptionsByOption(option...); err != nil {
return return
} }
defsys, err = newSys(options) Defsys, err = newSys(options)
return return
} }
func UpdateUser(data *pb.Cache_UserData) (err error) {
return defsys.UpdateUser(data)
}

8
sys/cache/user.go vendored
View File

@ -1,16 +1,14 @@
package cache package cache
import ( import (
"fmt"
"go_dreamfactory/pb" "go_dreamfactory/pb"
"github.com/liwei1dao/lego/core"
) )
const ( //Redis const ( //Redis
Redis_UserCache core.Redis_Key = "user:%d" //会话列表 Redis_UserCache string = "user:%d" //会话列表
) )
func (this *Cache) UpdateUser(data *pb.Cache_UserData) (err error) { func (this *Cache) UpdateUser(data *pb.Cache_UserData) (err error) {
return this.redis.Set(fmt.Sprintf(Redis_UserCache, data.UserData.UserId), data, 0)
return
} }

View File

@ -1,19 +1,37 @@
package cache package cache
import ( import (
"go_dreamfactory/pb"
"log"
"testing" "testing"
"github.com/liwei1dao/lego/sys/redis" "github.com/liwei1dao/lego/sys/redis"
"github.com/stretchr/testify/require"
) )
var rds redis.IRedis var cache *Cache
func TestMain(m *testing.M) { func TestMain(m *testing.M) {
redis.NewSys(redis.Redis_Cluster_Addr([]string{"10.0.0.9:9001", "10.0.0.9:9002", "10.0.0.9:9003", "10.0.1.45:9004", "10.0.1.45:9005", "10.0.1.45:9006"}), iredis, err := redis.NewSys(redis.Redis_Cluster_Addr([]string{"10.0.0.9:9001", "10.0.0.9:9002", "10.0.0.9:9003", "10.0.1.45:9004", "10.0.1.45:9005", "10.0.1.45:9006"}),
redis.SetRedis_Cluster_Password("")) redis.SetRedis_Cluster_Password(""), redis.SetRedisType(redis.Redis_Cluster))
if err != nil {
log.Fatal(err)
}
cache = &Cache{
redis: iredis,
}
defer m.Run() defer m.Run()
} }
func TestSet(t *testing.T) { func TestUpdateUser(t *testing.T) {
user := &pb.Cache_UserData{
SessionId: "1",
GatewayServiceId: "work",
UserData: &pb.DB_UserData{
UserId: 1,
Account: "aaa",
},
}
err := cache.UpdateUser(user)
require.Nil(t, err)
} }

View File

@ -4,20 +4,21 @@ import "go_dreamfactory/pb"
type ( type (
ISys interface { ISys interface {
FindUserByAccount(account string) (*pb.DB_UserData, error)
FindUserById(id uint32) (*pb.DB_UserData, error)
CreateUser(user *pb.DB_UserData) error
UpdateUser(data *pb.DB_UserData) (err error) UpdateUser(data *pb.DB_UserData) (err error)
} }
) )
const () var Defsys ISys
var defsys ISys
func OnInit(config map[string]interface{}, option ...Option) (err error) { func OnInit(config map[string]interface{}, option ...Option) (err error) {
var options Options var options Options
if options, err = newOptions(config, option...); err != nil { if options, err = newOptions(config, option...); err != nil {
return return
} }
defsys, err = newSys(options) Defsys, err = newSys(options)
return return
} }
@ -26,10 +27,6 @@ func NewSys(option ...Option) (sys ISys, err error) {
if options, err = newOptionsByOption(option...); err != nil { if options, err = newOptionsByOption(option...); err != nil {
return return
} }
defsys, err = newSys(options) Defsys, err = newSys(options)
return return
} }
func UpdateUser(data *pb.DB_UserData) (err error) {
return defsys.UpdateUser(data)
}

View File

@ -10,6 +10,7 @@ import (
"github.com/liwei1dao/lego/core" "github.com/liwei1dao/lego/core"
"github.com/liwei1dao/lego/sys/log" "github.com/liwei1dao/lego/sys/log"
"go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo/options"
) )
const ( //Redis const ( //Redis
@ -17,6 +18,10 @@ const ( //Redis
DB_UserIdTable core.SqlTable = "userid" //用户id表 DB_UserIdTable core.SqlTable = "userid" //用户id表
) )
type UserId struct {
UserId uint32 `bson:"_id"`
}
func (this *DB) FindUserByAccount(account string) (*pb.DB_UserData, error) { func (this *DB) FindUserByAccount(account string) (*pb.DB_UserData, error) {
filter := bson.D{ filter := bson.D{
{"account", account}, {"account", account},
@ -27,7 +32,7 @@ func (this *DB) FindUserByAccount(account string) (*pb.DB_UserData, error) {
return user, err return user, err
} }
func (this *DB) FindUserById(id int) (*pb.DB_UserData, error) { func (this *DB) FindUserById(id uint32) (*pb.DB_UserData, error) {
filter := bson.D{ filter := bson.D{
{"_id", id}, {"_id", id},
} }
@ -38,7 +43,14 @@ func (this *DB) FindUserById(id int) (*pb.DB_UserData, error) {
} }
func (this *DB) CreateUser(user *pb.DB_UserData) error { func (this *DB) CreateUser(user *pb.DB_UserData) error {
_, err := this.mgo.InsertOne(DB_UserTable, user) userId := &UserId{}
err := this.mgo.FindOneAndDelete(DB_UserIdTable, bson.M{}).Decode(userId)
if err != nil {
log.Errorf("find userId err :%v", err)
return err
}
user.UserId = userId.UserId
_, err = this.mgo.InsertOne(DB_UserTable, user)
return err return err
} }
@ -73,7 +85,15 @@ func (this DB) checkUserIdInit() (err error) {
} }
//更新用户数据到DB //更新用户数据到DB
func (this *DB) UpdateUser(data *pb.DB_UserData) (err error) { func (this *DB) UpdateUser(data *pb.DB_UserData) error {
err := this.mgo.FindOneAndUpdate(
return DB_UserTable,
bson.M{"_id": data.UserId},
bson.M{"$set": bson.M{
"niceName": data.NiceName,
"email": data.Email,
}},
options.FindOneAndUpdate().SetUpsert(false).SetReturnDocument(options.After),
).Decode(data)
return err
} }

View File

@ -27,9 +27,8 @@ func TestMain(m *testing.M) {
func TestCreate(t *testing.T) { func TestCreate(t *testing.T) {
user := &pb.DB_UserData{ user := &pb.DB_UserData{
UserId: 1, Account: "legu3",
Account: "legu1", NiceName: "乐谷3",
NiceName: "乐谷1",
Email: "1111@legu.com", Email: "1111@legu.com",
} }
@ -47,3 +46,14 @@ func TestFindOne(t *testing.T) {
assert.Equal(t, "legu1", user2.Account) assert.Equal(t, "legu1", user2.Account)
} }
func TestUpdate(t *testing.T) {
user := &pb.DB_UserData{
UserId: 10001,
Email: "new@qq.com",
}
err := db.UpdateUser(user)
require.Nil(t, err)
assert.Equal(t, "new@qq.com", user.Email)
}

17
utils/json.go Normal file
View File

@ -0,0 +1,17 @@
package utils
import (
"bytes"
jsoniter "github.com/json-iterator/go"
)
func JsonMarshal(i interface{}) ([]byte, error) {
return jsoniter.Marshal(i)
}
func JsonUnMarshal(data []byte, i interface{}) error {
d := jsoniter.NewDecoder(bytes.NewBuffer(data))
d.UseNumber()
return d.Decode(i)
}

41
utils/map.go Normal file
View File

@ -0,0 +1,41 @@
package utils
import (
"reflect"
"unicode"
"unicode/utf8"
)
func StructToMap(item interface{}) map[string]interface{} {
res := map[string]interface{}{}
if item == nil {
return res
}
v := reflect.TypeOf(item)
reflectValue := reflect.ValueOf(item)
reflectValue = reflect.Indirect(reflectValue)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
for i := 0; i < v.NumField(); i++ {
tag := v.Field(i).Tag.Get("json")
if !isExported(v.Field(i).Name) {
continue
}
field := reflectValue.Field(i).Interface()
if tag != "" && tag != "-" {
if v.Field(i).Type.Kind() == reflect.Struct {
res[tag] = StructToMap(field)
} else {
res[tag] = field
}
}
}
return res
}
func isExported(name string) bool {
rune, _ := utf8.DecodeRuneInString(name)
return unicode.IsUpper(rune)
}

View File

@ -1 +0,0 @@
package utils