Compare commits

...

2 Commits

Author SHA1 Message Date
zhaocy
42ca630ca9 login 2022-06-01 19:39:51 +08:00
liwei1dao
aeb1a1ab4d 优化用户路由祖册接口 2022-06-01 17:41:48 +08:00
19 changed files with 278 additions and 104 deletions

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

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

View File

@ -12,9 +12,9 @@ const (
)
const (
SM_GateModule core.M_Modules = "SM_GateModule" //gate模块 网关服务模块
SM_WebModule core.M_Modules = "SM_WebModule" //web模块
SM_LoginModule core.M_Modules = "SM_LoginModule" //web模块
SM_GateModule core.M_Modules = "gateway" //gate模块 网关服务模块
SM_WebModule core.M_Modules = "web" //web模块
SM_LoginModule core.M_Modules = "login" //web模块
)
const ( //Rpc

View File

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

View File

@ -2,8 +2,10 @@ package modules
import (
"context"
"fmt"
"go_dreamfactory/comm"
"reflect"
"strings"
"unicode"
"unicode/utf8"
@ -22,12 +24,14 @@ var typeOfError = reflect.TypeOf((*error)(nil)).Elem()
type MComp_GateComp struct {
cbase.ModuleCompBase
service base.IRPCXService
module core.IModule
comp core.IModuleComp
}
func (this *MComp_GateComp) Init(service core.IService, module core.IModule, comp core.IModuleComp, options core.IModuleOptions) (err error) {
this.ModuleCompBase.Init(service, module, comp, options)
this.service = service.(base.IRPCXService)
this.module = module
this.comp = comp
return
}
@ -86,7 +90,7 @@ func (this *MComp_GateComp) suitableMethods(scomp comm.ISC_GateRouteComp, typ re
if returnType := mtype.Out(0); returnType != typeOfError {
continue
}
scomp.RegisterRoute(mname, reflect.ValueOf(this.comp), replyType, method)
scomp.RegisterRoute(fmt.Sprintf("%s.%s", this.module.GetType(), strings.ToLower(mname)), reflect.ValueOf(this.comp), replyType, method)
}
}

View File

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

View File

@ -5,8 +5,11 @@ import (
"go_dreamfactory/comm"
"go_dreamfactory/modules"
"go_dreamfactory/pb"
"go_dreamfactory/sys/cache"
"go_dreamfactory/sys/db"
"github.com/liwei1dao/lego/sys/log"
"go.mongodb.org/mongo-driver/mongo"
)
type LoginComp struct {
@ -14,9 +17,40 @@ type LoginComp struct {
}
//登录
func (this *LoginComp) Login(ctx context.Context, session comm.IUserSession, rsp *pb.UserLoginReq) error {
log.Debugf("User - Login: session:%v rsp:%v", session.ToString(), rsp)
func (this *LoginComp) Login(ctx context.Context, session comm.IUserSession, req *pb.UserLoginReq) error {
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
}

26
modules/web/api_comp.go Normal file
View File

@ -0,0 +1,26 @@
package web
import (
"github.com/liwei1dao/lego/core"
"github.com/liwei1dao/lego/core/cbase"
"github.com/liwei1dao/lego/sys/gin"
"github.com/liwei1dao/lego/sys/gin/engine"
)
type Api_Comp struct {
cbase.ModuleCompBase
options *Options
gin gin.ISys
}
func (this *Api_Comp) Init(service core.IService, module core.IModule, comp core.IModuleComp, options core.IModuleOptions) (err error) {
err = this.ModuleCompBase.Init(service, module, comp, options)
this.options = options.(*Options)
this.gin, err = gin.NewSys(gin.SetListenPort(this.options.Port))
this.gin.GET("./test", this.test)
return
}
func (this *Api_Comp) test(c *engine.Context) {
}

View File

@ -3,7 +3,6 @@ package web
import (
"go_dreamfactory/comm"
"go_dreamfactory/modules"
"go_dreamfactory/sys/configure"
cfg "go_dreamfactory/sys/configure/structs"
"github.com/liwei1dao/lego/core"
@ -16,9 +15,9 @@ func NewModule() core.IModule {
type Web struct {
modules.ModuleBase
options *Options
table *cfg.TbItem
user_comp *User_Comp
options *Options
table *cfg.TbItem
api_comp *Api_Comp
}
func (this *Web) GetType() core.M_Modules {
@ -37,20 +36,20 @@ func (this *Web) Init(service core.IService, module core.IModule, options core.I
func (this *Web) Start() (err error) {
err = this.ModuleBase.Start()
var (
data interface{}
)
if err = configure.RegisterConfigure("tbitem.json", cfg.NewTbItem); err != nil {
return
}
if data, err = configure.GetConfigure("tbitem.json"); err != nil {
return
}
this.table = data.(*cfg.TbItem)
// var (
// data interface{}
// )
// if err = configure.RegisterConfigure("tbitem.json", cfg.NewTbItem); err != nil {
// return
// }
// if data, err = configure.GetConfigure("tbitem.json"); err != nil {
// return
// }
// this.table = data.(*cfg.TbItem)
return
}
func (this *Web) OnInstallComp() {
this.ModuleBase.OnInstallComp()
this.user_comp = this.RegisterComp(new(User_Comp)).(*User_Comp)
this.api_comp = this.RegisterComp(new(Api_Comp)).(*Api_Comp)
}

View File

@ -1,29 +0,0 @@
package web
import (
"context"
"go_dreamfactory/comm"
"go_dreamfactory/modules"
"go_dreamfactory/pb"
"github.com/liwei1dao/lego/core"
"github.com/liwei1dao/lego/sys/log"
)
type User_Comp struct {
modules.MComp_GateComp
}
func (this *User_Comp) Init(service core.IService, module core.IModule, comp core.IModuleComp, options core.IModuleOptions) (err error) {
this.MComp_GateComp.Init(service, module, comp, options)
return
}
func (this *User_Comp) Login(ctx context.Context, session comm.IUserSession, rsp *pb.UserLoginReq) error {
log.Debugf("User_Comp Login: session:%v rsp:%v", session.ToString(), rsp)
session.SendMsg("LogigResp", &pb.UserLoginResp{
Code: 200,
})
return nil
}

44
services/web/main.go Normal file
View File

@ -0,0 +1,44 @@
package main
import (
"flag"
"go_dreamfactory/modules/web"
"go_dreamfactory/services"
"github.com/liwei1dao/lego"
"github.com/liwei1dao/lego/base/rpcx"
"github.com/liwei1dao/lego/core"
)
var (
conf = flag.String("conf", "./conf/web_1.yaml", "获取需要启动的服务配置文件") //启动服务的Id
)
func main() {
flag.Parse()
s := NewService(
rpcx.SetConfPath(*conf),
rpcx.SetVersion("1.0.0.0"),
)
s.OnInstallComp( //装备组件
services.NewGateRouteComp(),
)
lego.Run(s, //运行模块
web.NewModule(),
)
}
func NewService(ops ...rpcx.Option) core.IService {
s := new(Service)
s.Configure(ops...)
return s
}
type Service struct {
services.ServiceBase
}
func (this *Service) InitSys() {
this.ServiceBase.InitSys()
}

10
sys/cache/core.go vendored
View File

@ -10,14 +10,14 @@ type (
const ()
var defsys ISys
var Defsys ISys
func OnInit(config map[string]interface{}, option ...Option) (err error) {
var options Options
if options, err = newOptions(config, option...); err != nil {
return
}
defsys, err = newSys(options)
Defsys, err = newSys(options)
return
}
@ -26,10 +26,8 @@ func NewSys(option ...Option) (sys ISys, err error) {
if options, err = newOptionsByOption(option...); err != nil {
return
}
defsys, err = newSys(options)
Defsys, err = newSys(options)
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
import (
"fmt"
"go_dreamfactory/pb"
"github.com/liwei1dao/lego/core"
)
const ( //Redis
Redis_UserCache core.Redis_Key = "user:%d" //会话列表
Redis_UserCache string = "user:%d" //会话列表
)
func (this *Cache) UpdateUser(data *pb.Cache_UserData) (err error) {
return
return this.redis.Set(fmt.Sprintf(Redis_UserCache, data.UserData.UserId), data, 0)
}

View File

@ -1,19 +1,37 @@
package cache
import (
"go_dreamfactory/pb"
"log"
"testing"
"github.com/liwei1dao/lego/sys/redis"
"github.com/stretchr/testify/require"
)
var rds redis.IRedis
var cache *Cache
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"}),
redis.SetRedis_Cluster_Password(""))
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.SetRedisType(redis.Redis_Cluster))
if err != nil {
log.Fatal(err)
}
cache = &Cache{
redis: iredis,
}
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 (
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)
}
)
const ()
var defsys ISys
var Defsys ISys
func OnInit(config map[string]interface{}, option ...Option) (err error) {
var options Options
if options, err = newOptions(config, option...); err != nil {
return
}
defsys, err = newSys(options)
Defsys, err = newSys(options)
return
}
@ -26,10 +27,6 @@ func NewSys(option ...Option) (sys ISys, err error) {
if options, err = newOptionsByOption(option...); err != nil {
return
}
defsys, err = newSys(options)
Defsys, err = newSys(options)
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/sys/log"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo/options"
)
const ( //Redis
@ -17,6 +18,10 @@ const ( //Redis
DB_UserIdTable core.SqlTable = "userid" //用户id表
)
type UserId struct {
UserId uint32 `bson:"_id"`
}
func (this *DB) FindUserByAccount(account string) (*pb.DB_UserData, error) {
filter := bson.D{
{"account", account},
@ -27,7 +32,7 @@ func (this *DB) FindUserByAccount(account string) (*pb.DB_UserData, error) {
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{
{"_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 {
_, 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
}
@ -73,7 +85,15 @@ func (this DB) checkUserIdInit() (err error) {
}
//更新用户数据到DB
func (this *DB) UpdateUser(data *pb.DB_UserData) (err error) {
return
func (this *DB) UpdateUser(data *pb.DB_UserData) error {
err := this.mgo.FindOneAndUpdate(
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) {
user := &pb.DB_UserData{
UserId: 1,
Account: "legu1",
NiceName: "乐谷1",
Account: "legu3",
NiceName: "乐谷3",
Email: "1111@legu.com",
}
@ -47,3 +46,14 @@ func TestFindOne(t *testing.T) {
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