14 Commits

33 changed files with 644 additions and 551 deletions

View File

@@ -2,12 +2,12 @@ package app
import ( import (
"fmt" "fmt"
"git.hlsq.asia/mmorpg/service-common/discover/common" "git.hlsq.asia/alex/service-common/discover/common"
"git.hlsq.asia/mmorpg/service-common/log" "git.hlsq.asia/alex/service-common/log"
"git.hlsq.asia/mmorpg/service-common/module" "git.hlsq.asia/alex/service-common/module"
"git.hlsq.asia/mmorpg/service-gateway/config" "git.hlsq.asia/alex/service-gateway/config"
"git.hlsq.asia/mmorpg/service-gateway/internal/global" "git.hlsq.asia/alex/service-gateway/internal/global"
"git.hlsq.asia/mmorpg/service-gateway/internal/grpc_server" "git.hlsq.asia/alex/service-gateway/internal/grpcserver"
"github.com/judwhite/go-svc" "github.com/judwhite/go-svc"
"sync" "sync"
) )
@@ -17,24 +17,18 @@ type Program struct {
} }
func (p *Program) Init(_ svc.Environment) error { func (p *Program) Init(_ svc.Environment) error {
base := &ModuleBase{} p.moduleList = append(p.moduleList, &module.Log{Cfg: config.Get().Log})
if err := base.Init(); err != nil { p.moduleList = append(p.moduleList, &module.DB{Cfg: config.Get().DB, AppName: config.Get().App.Name})
return err p.moduleList = append(p.moduleList, &module.Snowflake{})
}
p.moduleList = append(p.moduleList, base)
p.moduleList = append(p.moduleList, (&module.DB{}).Bind(config.Get().DB, common.KeyDiscoverServiceNameGateway))
p.moduleList = append(p.moduleList, &ModuleWebServer{}) p.moduleList = append(p.moduleList, &ModuleWebServer{})
p.moduleList = append(p.moduleList, &ModuleWebsocketServer{}) p.moduleList = append(p.moduleList, &ModuleWebsocketServer{})
p.moduleList = append(p.moduleList, &ModuleLoginQueue{}) p.moduleList = append(p.moduleList, &ModuleLoginQueue{})
p.moduleList = append(p.moduleList, (&module.Grpc{}).Bind(grpc_server.NewServer(config.Get().Serve.Grpc))) p.moduleList = append(p.moduleList, &module.Grpc{Server: grpcserver.NewServer(config.Get().Serve.Grpc)})
p.moduleList = append(p.moduleList, (&module.Prometheus{}).Bind(config.Get().Metric)) p.moduleList = append(p.moduleList, &module.Prometheus{Cfg: config.Get().Metric})
p.moduleList = append(p.moduleList, (&module.Tracer{}).Bind(config.Get().Metric, common.KeyDiscoverServiceNameGateway)) p.moduleList = append(p.moduleList, &module.Tracer{Cfg: config.Get().Metric, ServiceName: common.KeyDiscoverServiceNameGateway})
p.moduleList = append(p.moduleList, &module.Discover{}) p.moduleList = append(p.moduleList, &module.Discover{})
for i, m := range p.moduleList { for _, m := range p.moduleList {
if i == 0 {
continue
}
if err := m.Init(); err != nil { if err := m.Init(); err != nil {
return err return err
} }

View File

@@ -1,27 +0,0 @@
package app
import (
"git.hlsq.asia/mmorpg/service-common/log"
"git.hlsq.asia/mmorpg/service-common/module"
"git.hlsq.asia/mmorpg/service-common/utils"
"git.hlsq.asia/mmorpg/service-gateway/config"
"math/rand"
)
// ModuleBase 基础模块,或者一些零散的模块
type ModuleBase struct {
module.DefaultModule
}
func (m *ModuleBase) Init() error {
// 配置
if err := config.LoadConfig(); err != nil {
return err
}
cfg := config.Get()
// 日志
log.Init(cfg.Log.Debug, cfg.Log.MaxSize, cfg.Log.MaxBackups, cfg.Log.MaxAge, cfg.Log.Level)
// 雪花
utils.InitSnowflake(int64(rand.Intn(1000)))
return nil
}

View File

@@ -1,9 +1,9 @@
package app package app
import ( import (
"git.hlsq.asia/mmorpg/service-common/module" "git.hlsq.asia/alex/service-common/module"
"git.hlsq.asia/mmorpg/service-gateway/internal/global" "git.hlsq.asia/alex/service-gateway/internal/global"
"git.hlsq.asia/mmorpg/service-gateway/internal/handler/ws_handler/login" "git.hlsq.asia/alex/service-gateway/internal/handler/wshandler/login"
"runtime" "runtime"
"sync" "sync"
) )

View File

@@ -4,10 +4,10 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"git.hlsq.asia/mmorpg/service-common/log" "git.hlsq.asia/alex/service-common/log"
"git.hlsq.asia/mmorpg/service-common/module" "git.hlsq.asia/alex/service-common/module"
"git.hlsq.asia/mmorpg/service-gateway/config" "git.hlsq.asia/alex/service-gateway/config"
"git.hlsq.asia/mmorpg/service-gateway/internal/net/http_gateway" "git.hlsq.asia/alex/service-gateway/internal/net/httpgateway"
"net/http" "net/http"
"sync" "sync"
) )
@@ -30,9 +30,10 @@ func (m *ModuleWebServer) Start(ready *sync.WaitGroup) error {
defer m.wg.Done() defer m.wg.Done()
m.server = &http.Server{ m.server = &http.Server{
Addr: fmt.Sprintf("%v:%v", config.Get().Serve.Http.Address, config.Get().Serve.Http.Port), Addr: fmt.Sprintf("%v:%v", config.Get().Serve.Http.Address, config.Get().Serve.Http.Port),
Handler: http_gateway.InitRouter(), Handler: httpgateway.InitRouter(),
} }
ready.Done() ready.Done()
log.Infof("http server start, addr: %v", m.server.Addr)
if err := m.server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { if err := m.server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Errorf("http server failed: %v", err.Error()) log.Errorf("http server failed: %v", err.Error())
} }

View File

@@ -2,11 +2,11 @@ package app
import ( import (
"fmt" "fmt"
"git.hlsq.asia/mmorpg/service-common/log" "git.hlsq.asia/alex/service-common/log"
"git.hlsq.asia/mmorpg/service-common/module" "git.hlsq.asia/alex/service-common/module"
"git.hlsq.asia/mmorpg/service-common/net/socket/websocket" "git.hlsq.asia/alex/service-common/net/socket/websocket"
"git.hlsq.asia/mmorpg/service-gateway/config" "git.hlsq.asia/alex/service-gateway/config"
"git.hlsq.asia/mmorpg/service-gateway/internal/net/ws_gateway" "git.hlsq.asia/alex/service-gateway/internal/net/wsgateway"
"github.com/panjf2000/gnet/v2" "github.com/panjf2000/gnet/v2"
"sync" "sync"
"time" "time"
@@ -22,7 +22,7 @@ type ModuleWebsocketServer struct {
func (m *ModuleWebsocketServer) Init() error { func (m *ModuleWebsocketServer) Init() error {
m.wg = &sync.WaitGroup{} m.wg = &sync.WaitGroup{}
m.server = websocket.NewWSServer( m.server = websocket.NewWSServer(
&ws_gateway.GatewayWsServer{}, &wsgateway.GatewayWsServer{},
log.GetLogger().Named("ws_server"), log.GetLogger().Named("ws_server"),
5*time.Second, 5*time.Second,
) )
@@ -34,6 +34,7 @@ func (m *ModuleWebsocketServer) Start(ready *sync.WaitGroup) error {
go func() { go func() {
defer m.wg.Done() defer m.wg.Done()
ready.Done() ready.Done()
log.Infof("websocket server start, port: %v", config.Get().Serve.Socket.Web.Port)
_ = m.server.Run( _ = m.server.Run(
fmt.Sprintf("tcp4://0.0.0.0:%v", config.Get().Serve.Socket.Web.Port), fmt.Sprintf("tcp4://0.0.0.0:%v", config.Get().Serve.Socket.Web.Port),
true, true,

View File

@@ -13,19 +13,19 @@ metric:
address: "0.0.0.0" address: "0.0.0.0"
port: 18504 port: 18504
jaeger: jaeger:
endpoint: "localhost:4317" endpoint: "127.0.0.1:4317"
db: db:
etcd: etcd:
endpoints: [ "localhost:2379" ] endpoints: [ "127.0.0.1:2379" ]
redis: redis:
addr: "localhost:6379" addr: "127.0.0.1:6379"
password: "lQ7aM8oB6lK0iD5k" password: "lQ7aM8oB6lK0iD5k"
db: 0 db: 0
serve: serve:
grpc: grpc:
address: "10.0.40.199" address: "127.0.0.1"
port: 18500 port: 18500
ttl: 20 ttl: 20
socket: socket:
@@ -40,6 +40,5 @@ serve:
port: 18503 port: 18503
auth: auth:
secret: "bMa3mU4oCsX2KBex5o7GzwSnACpumFq3SdlDXYZgVTU=" shortExpire: 3600
shortExpire: 60 longExpire: 604800
longExpire: 10080

View File

@@ -1,6 +1,6 @@
package config package config
import "git.hlsq.asia/mmorpg/service-common/config" import "git.hlsq.asia/alex/service-common/config"
const path = "./config" const path = "./config"
@@ -14,9 +14,8 @@ type Config struct {
} }
type AuthConfig struct { type AuthConfig struct {
Secret string `yaml:"secret"` ShortExpire int64 `yaml:"shortExpire"`
ShortExpire int64 `yaml:"shortExpire"` LongExpire int64 `yaml:"longExpire"`
LongExpire int64 `yaml:"longExpire"`
} }
var cfg *Config var cfg *Config

View File

@@ -40,6 +40,5 @@ serve:
port: 18503 port: 18503
auth: auth:
secret: "bMa3mU4oCsX2KBex5o7GzwSnACpumFq3SdlDXYZgVTU=" shortExpire: 3600
shortExpire: 15 longExpire: 604800
longExpire: 10080

2
deploy/Jenkinsfile vendored
View File

@@ -3,7 +3,7 @@ pipeline {
environment { environment {
// 仓库 // 仓库
REPO_URL = 'https://git.hlsq.asia/mmorpg/service-gateway.git' REPO_URL = 'https://git.hlsq.asia/alex/service-gateway.git'
REPO_CREDENTIALS_ID = '80805ba2-f4ac-4d84-aee6-d4cce5fc0a96' REPO_CREDENTIALS_ID = '80805ba2-f4ac-4d84-aee6-d4cce5fc0a96'
// Registry // Registry

8
go.mod
View File

@@ -1,19 +1,19 @@
module git.hlsq.asia/mmorpg/service-gateway module git.hlsq.asia/alex/service-gateway
go 1.24.0 go 1.24.0
require ( require (
bou.ke/monkey v1.0.2 bou.ke/monkey v1.0.2
git.hlsq.asia/mmorpg/service-common v0.0.0-20260123132258-4d661d08134e git.hlsq.asia/alex/service-common master
github.com/alicebob/miniredis/v2 v2.35.0 github.com/alicebob/miniredis/v2 v2.35.0
github.com/gin-contrib/cors v1.7.6 github.com/gin-contrib/cors v1.7.6
github.com/gin-gonic/gin v1.11.0 github.com/gin-gonic/gin v1.11.0
github.com/golang/mock v1.6.0 github.com/golang/mock v1.6.0
github.com/google/uuid v1.6.0
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3
github.com/judwhite/go-svc v1.2.1 github.com/judwhite/go-svc v1.2.1
github.com/panjf2000/gnet/v2 v2.9.7 github.com/panjf2000/gnet/v2 v2.9.7
github.com/prometheus/client_golang v1.20.5 github.com/prometheus/client_golang v1.20.5
github.com/redis/go-redis/v9 v9.10.0
github.com/stretchr/testify v1.11.1 github.com/stretchr/testify v1.11.1
go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin v0.64.0 go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin v0.64.0
go.uber.org/zap v1.27.0 go.uber.org/zap v1.27.0
@@ -58,7 +58,6 @@ require (
github.com/golang-jwt/jwt/v5 v5.3.0 // indirect github.com/golang-jwt/jwt/v5 v5.3.0 // indirect
github.com/golang/protobuf v1.5.4 // indirect github.com/golang/protobuf v1.5.4 // indirect
github.com/golang/snappy v0.0.4 // indirect github.com/golang/snappy v0.0.4 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hashicorp/go-uuid v1.0.3 // indirect github.com/hashicorp/go-uuid v1.0.3 // indirect
github.com/jcmturner/aescts/v2 v2.0.0 // indirect github.com/jcmturner/aescts/v2 v2.0.0 // indirect
github.com/jcmturner/dnsutils/v2 v2.0.0 // indirect github.com/jcmturner/dnsutils/v2 v2.0.0 // indirect
@@ -86,6 +85,7 @@ require (
github.com/quic-go/qpack v0.6.0 // indirect github.com/quic-go/qpack v0.6.0 // indirect
github.com/quic-go/quic-go v0.57.1 // indirect github.com/quic-go/quic-go v0.57.1 // indirect
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 // indirect github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 // indirect
github.com/redis/go-redis/v9 v9.10.0 // indirect
github.com/sagikazarmark/locafero v0.11.0 // indirect github.com/sagikazarmark/locafero v0.11.0 // indirect
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
github.com/spf13/afero v1.15.0 // indirect github.com/spf13/afero v1.15.0 // indirect

6
go.sum
View File

@@ -2,8 +2,10 @@ bou.ke/monkey v1.0.2 h1:kWcnsrCNUatbxncxR/ThdYqbytgOIArtYWqcQLQzKLI=
bou.ke/monkey v1.0.2/go.mod h1:OqickVX3tNx6t33n1xvtTtu85YN5s6cKwVug+oHMaIA= bou.ke/monkey v1.0.2/go.mod h1:OqickVX3tNx6t33n1xvtTtu85YN5s6cKwVug+oHMaIA=
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
git.hlsq.asia/mmorpg/service-common v0.0.0-20260123132258-4d661d08134e h1:jcDwaL280D5BVGCfcIC3mQCjmwPz5fxX7NO1qf6nAIo= git.hlsq.asia/alex/service-common v0.0.0-20260207051302-0ca8a0ccbb14 h1:4r3tNWRzGVY3Xx6UiGjJJnwoMoWlVqbyGrljxl5d/nQ=
git.hlsq.asia/mmorpg/service-common v0.0.0-20260123132258-4d661d08134e/go.mod h1:mMhZcumphj6gaVTppVYsMTkd+5HupmQgAc53Pd4MH9I= git.hlsq.asia/alex/service-common v0.0.0-20260207051302-0ca8a0ccbb14/go.mod h1:mMhZcumphj6gaVTppVYsMTkd+5HupmQgAc53Pd4MH9I=
git.hlsq.asia/alex/service-common v0.0.0-20260211064821-558677bc3a2e h1:MNVS1NXNVn4DeTZPcvvA8YFM8afCzZedLPUYMffNgZs=
git.hlsq.asia/alex/service-common v0.0.0-20260211064821-558677bc3a2e/go.mod h1:mMhZcumphj6gaVTppVYsMTkd+5HupmQgAc53Pd4MH9I=
github.com/BurntSushi/toml v1.2.0 h1:Rt8g24XnyGTyglgET/PRUNlrUeu9F5L+7FilkXfZgs0= github.com/BurntSushi/toml v1.2.0 h1:Rt8g24XnyGTyglgET/PRUNlrUeu9F5L+7FilkXfZgs0=
github.com/BurntSushi/toml v1.2.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/BurntSushi/toml v1.2.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/IBM/sarama v1.46.3 h1:njRsX6jNlnR+ClJ8XmkO+CM4unbrNr/2vB5KK6UA+IE= github.com/IBM/sarama v1.46.3 h1:njRsX6jNlnR+ClJ8XmkO+CM4unbrNr/2vB5KK6UA+IE=

View File

@@ -10,11 +10,12 @@ const (
ServiceStatusStopping // 停止中 ServiceStatusStopping // 停止中
) )
var GatewaySID string var GatewaySID int64
const ( const (
KeyGatewayAccessToken = "gateway:token:access:%v" KeyGatewayAccessToken = "gateway:token:access:"
KeyGatewayRefreshToken = "gateway:token:refresh:%v" KeyGatewayRefreshToken = "gateway:token:refresh:"
KeyGatewaySession = "gateway:session:"
KeyGatewayInfo = "gateway:info:%v" KeyGatewayInfo = "gateway:info:%v"
HFieldInfoGatewaySID = "gateway_sid" HFieldInfoGatewaySID = "gateway_sid"

View File

@@ -1,17 +1,17 @@
package grpc_server package grpcserver
import ( import (
"context" "context"
"git.hlsq.asia/mmorpg/service-common/log" "git.hlsq.asia/alex/service-common/log"
"git.hlsq.asia/mmorpg/service-common/proto/rs/grpc_pb" "git.hlsq.asia/alex/service-common/proto/rs/rspb"
"git.hlsq.asia/mmorpg/service-common/proto/ss/ss_pb" "git.hlsq.asia/alex/service-common/proto/ss/sspb"
"git.hlsq.asia/mmorpg/service-gateway/internal/global" "git.hlsq.asia/alex/service-gateway/internal/global"
"git.hlsq.asia/mmorpg/service-gateway/internal/handler/ws_handler/client" "git.hlsq.asia/alex/service-gateway/internal/handler/wshandler/client"
"google.golang.org/protobuf/proto" "google.golang.org/protobuf/proto"
"sync" "sync"
) )
func (s *Server) ToClient(server grpc_pb.Gateway_ToClientServer) error { func (s *Server) ToClient(server rspb.Gateway_ToClientServer) error {
wg := &sync.WaitGroup{} wg := &sync.WaitGroup{}
wg.Add(1) wg.Add(1)
go func() { go func() {
@@ -25,15 +25,15 @@ func (s *Server) ToClient(server grpc_pb.Gateway_ToClientServer) error {
if args, err := server.Recv(); err != nil { if args, err := server.Recv(); err != nil {
return return
} else { } else {
if args.USN == "" { if args.USN == -1 {
//utils.WorkerPool(ws_handler.UserMgr.GetAllInterface(), func(task interface{}) { //utils.WorkerPool(ws_handler.UserMgr.GetAllInterface(), func(task interface{}) {
// client := task.(*ws_handler.Client) // client := task.(*ws_handler.Client)
// client.WriteBytes(ss_pb.MessageID(args.MessageID), args.Payload) // client.WriteBytes(ss_pb.MessageID(args.MessageID), args.Payload)
//}) //})
data, err := proto.Marshal(&ss_pb.Message{ data, err := proto.Marshal(&sspb.Message{
ID: ss_pb.MessageID(args.MessageID), ID: sspb.MessageID(args.MessageID),
Payload: args.Payload, Payload: args.Payload,
}) })
if err != nil { if err != nil {
@@ -51,7 +51,7 @@ func (s *Server) ToClient(server grpc_pb.Gateway_ToClientServer) error {
//} //}
} else { } else {
if cli := client.UserMgr.GetByUSN(args.USN); cli != nil { if cli := client.UserMgr.GetByUSN(args.USN); cli != nil {
cli.WriteBytes(ss_pb.MessageID(args.MessageID), args.Payload) cli.WriteBytes(sspb.MessageID(args.MessageID), args.Payload)
global.FlowCounter.Add(float64(len(args.Payload))) global.FlowCounter.Add(float64(len(args.Payload)))
} }
} }
@@ -59,12 +59,12 @@ func (s *Server) ToClient(server grpc_pb.Gateway_ToClientServer) error {
} }
}() }()
wg.Wait() wg.Wait()
return server.SendAndClose(&grpc_pb.ToClientResp{}) return server.SendAndClose(&rspb.ToClientResp{})
} }
func (s *Server) KickUser(ctx context.Context, req *grpc_pb.KickUserReq) (*grpc_pb.KickUserResp, error) { func (s *Server) KickUser(ctx context.Context, req *rspb.KickUserReq) (*rspb.KickUserResp, error) {
if cli := client.UserMgr.GetByUSN(req.USN); cli != nil { if cli := client.UserMgr.GetByUSN(req.USN); cli != nil {
cli.CloseClient() cli.CloseClient()
} }
return &grpc_pb.KickUserResp{}, nil return &rspb.KickUserResp{}, nil
} }

View File

@@ -1,16 +1,16 @@
package grpc_server package grpcserver
import ( import (
"git.hlsq.asia/mmorpg/service-common/config" "git.hlsq.asia/alex/service-common/config"
"git.hlsq.asia/mmorpg/service-common/discover/common" "git.hlsq.asia/alex/service-common/discover/common"
"git.hlsq.asia/mmorpg/service-common/net/grpc/service" "git.hlsq.asia/alex/service-common/net/grpc/service"
"git.hlsq.asia/mmorpg/service-common/proto/rs/grpc_pb" "git.hlsq.asia/alex/service-common/proto/rs/rspb"
"git.hlsq.asia/mmorpg/service-gateway/internal/global" "git.hlsq.asia/alex/service-gateway/internal/global"
"google.golang.org/grpc" "google.golang.org/grpc"
) )
type Server struct { type Server struct {
grpc_pb.UnimplementedGatewayServer rspb.UnimplementedGatewayServer
service.Base service.Base
} }
@@ -34,7 +34,7 @@ func (s *Server) OnCustomGrpcServerOption() []grpc.ServerOption {
func (s *Server) OnInit(serve *grpc.Server) { func (s *Server) OnInit(serve *grpc.Server) {
global.GatewaySID = s.SID global.GatewaySID = s.SID
grpc_pb.RegisterGatewayServer(serve, s) rspb.RegisterGatewayServer(serve, s)
} }
func (s *Server) OnClose() { func (s *Server) OnClose() {

View File

@@ -1,139 +0,0 @@
package http_handler
import (
"context"
"fmt"
"git.hlsq.asia/mmorpg/service-common/db/redis"
"git.hlsq.asia/mmorpg/service-common/log"
"git.hlsq.asia/mmorpg/service-common/net/grpc/grpc_client"
"git.hlsq.asia/mmorpg/service-common/net/http/http_resp"
"git.hlsq.asia/mmorpg/service-common/proto/rs/grpc_pb"
"git.hlsq.asia/mmorpg/service-common/utils"
"git.hlsq.asia/mmorpg/service-gateway/config"
"git.hlsq.asia/mmorpg/service-gateway/internal/global"
"github.com/gin-gonic/gin"
"time"
)
// 这个模块处理用户登录
type LoginReq struct {
Phone string `json:"phone"` // 手机号
Code string `json:"code"` // 验证码
WxMiniCode string `json:"wxMiniCode"` // 微信小程序登录
}
type LoginResp struct {
USN string `json:"usn"`
Name string `json:"name"`
AccessToken string `json:"accessToken"`
RefreshToken string `json:"refreshToken"`
}
func Login(c *gin.Context) {
req := &LoginReq{}
if err := c.ShouldBindJSON(req); err != nil {
http_resp.JsonBadRequest(c)
return
}
client, err := grpc_client.UserNewClientLB()
if err != nil {
log.Errorf("Login UserNewClientLB error: %v", err)
http_resp.JsonOK(c, http_resp.Error(http_resp.Failed))
return
}
usn, name := "", ""
if req.Phone != "" {
// TODO 校验验证码
login, err := client.PhoneLogin(c, &grpc_pb.PhoneLoginReq{
Phone: req.Phone,
Code: req.Code,
})
if err != nil {
log.Errorf("Login PhoneLogin error: %v", err)
http_resp.JsonOK(c, http_resp.Error(http_resp.Failed))
return
}
usn, name = login.USN, login.Name
} else if req.WxMiniCode != "" {
login, err := client.WxMiniLogin(c, &grpc_pb.WxMiniLoginReq{
Code: req.WxMiniCode,
})
if err != nil {
log.Errorf("Login WxMiniLogin error: %v", err)
http_resp.JsonOK(c, http_resp.Error(http_resp.Failed))
return
}
usn, name = login.USN, login.Name
} else {
http_resp.JsonBadRequest(c)
return
}
at, rt, err := genToken(c, usn)
http_resp.JsonOK(c, http_resp.Success(&LoginResp{
USN: usn,
Name: name,
AccessToken: at,
RefreshToken: rt,
}))
}
type RefreshTokenReq struct {
RefreshToken string `json:"refreshToken" binding:"required,min=1"`
}
type RefreshTokenResp struct {
AccessToken string `json:"accessToken"`
RefreshToken string `json:"refreshToken"`
}
func RefreshToken(c *gin.Context) {
req := &RefreshTokenReq{}
if err := c.ShouldBindJSON(req); err != nil {
http_resp.JsonBadRequest(c)
return
}
claims, err := utils.ParseToken(req.RefreshToken, config.Get().Auth.Secret)
if err != nil {
http_resp.JsonUnauthorized(c)
return
}
if redis.GetClient().Get(c, fmt.Sprintf(global.KeyGatewayRefreshToken, claims.USN)).Val() != req.RefreshToken {
http_resp.JsonUnauthorized(c)
return
}
at, rt, err := genToken(c, claims.USN)
if err != nil {
log.Errorf("RefreshToken genToken error: %v, usn: %v", err, claims.USN)
http_resp.JsonOK(c, http_resp.Error(http_resp.Failed))
return
}
http_resp.JsonOK(c, http_resp.Success(&RefreshTokenResp{
AccessToken: at,
RefreshToken: rt,
}))
}
func genToken(ctx context.Context, usn string) (string, string, error) {
at, err := genTokenOne(ctx, global.KeyGatewayAccessToken, usn, time.Duration(config.Get().Auth.ShortExpire)*time.Minute)
if err != nil {
return "", "", err
}
rt, err := genTokenOne(ctx, global.KeyGatewayRefreshToken, usn, time.Duration(config.Get().Auth.LongExpire)*time.Minute)
if err != nil {
return "", "", err
}
return at, rt, nil
}
func genTokenOne(ctx context.Context, key string, usn string, ttl time.Duration) (string, error) {
token, err := utils.GenToken(usn, config.Get().Auth.Secret, ttl)
if err != nil {
return "", err
}
redis.GetClient().Set(ctx, fmt.Sprintf(key, usn), token, ttl)
return token, err
}

View File

@@ -1,172 +0,0 @@
package http_handler
import (
"bou.ke/monkey"
"context"
"fmt"
"git.hlsq.asia/mmorpg/service-common/db/redis"
"git.hlsq.asia/mmorpg/service-common/net/grpc/grpc_client"
"git.hlsq.asia/mmorpg/service-common/net/http/http_resp"
"git.hlsq.asia/mmorpg/service-common/proto/rs/grpc_pb"
"git.hlsq.asia/mmorpg/service-common/proto/rs/grpc_pb/mocks"
"git.hlsq.asia/mmorpg/service-common/utils"
"git.hlsq.asia/mmorpg/service-gateway/internal/global"
"git.hlsq.asia/mmorpg/service-gateway/internal/testutil"
"github.com/gin-gonic/gin"
"github.com/golang/mock/gomock"
redis2 "github.com/redis/go-redis/v9"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
"net/http"
"strconv"
"testing"
)
type LoginTestSuite struct {
testutil.TestSuite
}
func (ts *LoginTestSuite) TestGenToken() {
usn := utils.RandInt(1, 100000000)
at, rt, err := genToken(context.Background(), strconv.Itoa(usn))
ts.Assert().NoError(err)
redisAt := redis.GetClient().Get(context.Background(), fmt.Sprintf(global.KeyGatewayAccessToken, usn)).Val()
ts.Assert().Equal(at, redisAt)
redisRt := redis.GetClient().Get(context.Background(), fmt.Sprintf(global.KeyGatewayRefreshToken, usn)).Val()
ts.Assert().Equal(rt, redisRt)
}
func (ts *LoginTestSuite) TestLogin() {
gin.SetMode(gin.TestMode)
ts.Run("ShouldBindJSON Failed", func() {
w, c := utils.CreateTestContext("POST", "/", &LoginReq{
Phone: "",
Code: "",
})
Login(c)
utils.AssertResponse(&ts.Suite, w, http.StatusBadRequest, http_resp.ParamError)
})
ts.Run("UserNewClientLB Failed", func() {
monkey.Patch(grpc_client.UserNewClientLB, func() (grpc_pb.UserClient, error) {
return nil, assert.AnError
})
defer monkey.Unpatch(grpc_client.UserNewClientLB)
w, c := utils.CreateTestContext("POST", "/", &LoginReq{
Phone: "13800000000",
Code: "1234",
})
Login(c)
utils.AssertResponse(&ts.Suite, w, http.StatusOK, http_resp.Failed)
})
ts.Run("Login Failed", func() {
ctrl := gomock.NewController(ts.T())
defer ctrl.Finish()
client := mocks.NewMockUserClient(ctrl)
client.EXPECT().
PhoneLogin(gomock.Any(), gomock.Any()).
Return(nil, fmt.Errorf("gRPC failed"))
monkey.Patch(grpc_client.UserNewClientLB, func() (grpc_pb.UserClient, error) {
return client, nil
})
defer monkey.Unpatch(grpc_client.UserNewClientLB)
w, c := utils.CreateTestContext("POST", "/", &LoginReq{
Phone: "13800000000",
Code: "1234",
})
Login(c)
utils.AssertResponse(&ts.Suite, w, http.StatusOK, http_resp.Failed)
})
ts.Run("OK", func() {
ctrl := gomock.NewController(ts.T())
defer ctrl.Finish()
client := mocks.NewMockUserClient(ctrl)
client.EXPECT().
PhoneLogin(gomock.Any(), gomock.Any()).
Return(&grpc_pb.PhoneLoginResp{USN: "1", Name: "hh"}, nil)
monkey.Patch(grpc_client.UserNewClientLB, func() (grpc_pb.UserClient, error) {
return client, nil
})
defer monkey.Unpatch(grpc_client.UserNewClientLB)
w, c := utils.CreateTestContext("POST", "/", &LoginReq{
Phone: "13800000000",
Code: "1234",
})
Login(c)
utils.AssertResponse(&ts.Suite, w, http.StatusOK, http_resp.OK)
})
}
func (ts *LoginTestSuite) TestRefreshToken() {
gin.SetMode(gin.TestMode)
ts.Run("ShouldBindJSON Failed", func() {
w, c := utils.CreateTestContext("POST", "/", &RefreshTokenReq{
RefreshToken: "",
})
RefreshToken(c)
utils.AssertResponse(&ts.Suite, w, http.StatusBadRequest, http_resp.ParamError)
})
ts.Run("ParseToken Failed", func() {
monkey.Patch(utils.ParseToken, func(tokenString string, secret string) (*utils.Claims, error) {
return nil, assert.AnError
})
defer monkey.Unpatch(utils.ParseToken)
w, c := utils.CreateTestContext("POST", "/", &RefreshTokenReq{
RefreshToken: "abc",
})
RefreshToken(c)
utils.AssertResponse(&ts.Suite, w, http.StatusOK, http_resp.TokenInvalid)
})
ts.Run("Redis Get Failed", func() {
monkey.Patch(utils.ParseToken, func(tokenString string, secret string) (*utils.Claims, error) {
if tokenString == "abc" {
return &utils.Claims{USN: "1"}, nil
}
return nil, assert.AnError
})
defer monkey.Unpatch(utils.ParseToken)
redis.GetClient().Set(context.Background(), fmt.Sprintf(global.KeyGatewayRefreshToken, 1), "ab", redis2.KeepTTL)
w, c := utils.CreateTestContext("POST", "/", &RefreshTokenReq{
RefreshToken: "abc",
})
RefreshToken(c)
utils.AssertResponse(&ts.Suite, w, http.StatusOK, http_resp.TokenInvalid)
})
ts.Run("OK", func() {
monkey.Patch(utils.ParseToken, func(tokenString string, secret string) (*utils.Claims, error) {
if tokenString == "abc" {
return &utils.Claims{USN: "1"}, nil
}
return nil, assert.AnError
})
defer monkey.Unpatch(utils.ParseToken)
redis.GetClient().Set(context.Background(), fmt.Sprintf(global.KeyGatewayRefreshToken, 1), "abc", redis2.KeepTTL)
w, c := utils.CreateTestContext("POST", "/", &RefreshTokenReq{
RefreshToken: "abc",
})
RefreshToken(c)
utils.AssertResponse(&ts.Suite, w, http.StatusOK, http_resp.OK)
})
}
func TestLoginTestSuite(t *testing.T) {
suite.Run(t, &LoginTestSuite{})
}

View File

@@ -0,0 +1,155 @@
package httphandler
import (
"git.hlsq.asia/alex/service-common/db/redis"
"git.hlsq.asia/alex/service-common/log"
"git.hlsq.asia/alex/service-common/net/grpc/grpcclient"
"git.hlsq.asia/alex/service-common/net/http/httpresp"
"git.hlsq.asia/alex/service-common/proto/rs/rspb"
"git.hlsq.asia/alex/service-common/utils"
"git.hlsq.asia/alex/service-gateway/internal/global"
"github.com/gin-gonic/gin"
)
// 这个模块处理用户登录
type LoginReq struct {
Phone string `json:"phone"` // 手机号
Code string `json:"code"` // 验证码
WxMiniCode string `json:"wxMiniCode"` // 微信小程序登录
}
type LoginResp struct {
USN int64 `json:"usn"`
Name string `json:"name"`
AccessToken string `json:"accessToken"`
RefreshToken string `json:"refreshToken"`
}
func Login(c *gin.Context) {
req := &LoginReq{}
if err := c.ShouldBindJSON(req); err != nil {
httpresp.JsonBadRequest(c)
return
}
client, err := grpcclient.UserNewClientLB()
if err != nil {
log.Errorf("Login UserNewClientLB error: %v", err)
httpresp.JsonOK(c, httpresp.Error(httpresp.Failed))
return
}
usn, name := int64(0), ""
if req.Phone != "" {
// TODO 校验验证码
login, err := client.PhoneLogin(c, &rspb.PhoneLoginReq{
Phone: req.Phone,
Code: req.Code,
})
if err != nil {
log.Errorf("Login PhoneLogin error: %v", err)
httpresp.JsonOK(c, httpresp.Error(httpresp.Failed))
return
}
usn, name = login.USN, login.Name
} else if req.WxMiniCode != "" {
login, err := client.WxMiniLogin(c, &rspb.WxMiniLoginReq{
Code: req.WxMiniCode,
})
if err != nil {
log.Errorf("Login WxMiniLogin error: %v", err)
httpresp.JsonOK(c, httpresp.Error(httpresp.Failed))
return
}
usn, name = login.USN, login.Name
} else {
httpresp.JsonBadRequest(c)
return
}
at, rt, err := sessionLogin(c, usn)
if err != nil {
log.Errorf("Login sessionLogin error: %v, usn: %v", err, usn)
httpresp.JsonOK(c, httpresp.Error(httpresp.Failed))
return
}
httpresp.JsonOK(c, httpresp.Success(&LoginResp{
USN: usn,
Name: name,
AccessToken: at,
RefreshToken: rt,
}))
}
type RefreshTokenReq struct {
RefreshToken string `json:"refreshToken"`
}
type RefreshTokenResp struct {
AccessToken string `json:"accessToken"`
RefreshToken string `json:"refreshToken"`
}
func RefreshToken(c *gin.Context) {
req := &RefreshTokenReq{}
if err := c.ShouldBindJSON(req); err != nil {
httpresp.JsonBadRequest(c)
return
}
if req.RefreshToken == "" {
cookie, err := c.Cookie("refresh_token")
if err != nil {
httpresp.JsonUnauthorized(c)
return
}
req.RefreshToken = cookie
}
usn, _ := redis.GetClient().HGet(c, global.KeyGatewayRefreshToken+req.RefreshToken, (&utils.UserSession{}).GetUsnKey()).Int64()
if usn == 0 {
httpresp.JsonUnauthorized(c)
return
}
if err := sessionLogout(c, req.RefreshToken); err != nil {
log.Errorf("RefreshToken sessionLogout error: %v, usn: %v", err, usn)
}
at, rt, err := sessionLogin(c, usn)
if err != nil {
log.Errorf("RefreshToken sessionLogin error: %v, usn: %v", err, usn)
httpresp.JsonOK(c, httpresp.Error(httpresp.Failed))
return
}
httpresp.JsonOK(c, httpresp.Success(&RefreshTokenResp{
AccessToken: at,
RefreshToken: rt,
}))
}
type LogoutReq struct {
RefreshToken string `json:"refreshToken"`
}
type LogoutResp struct {
}
func Logout(c *gin.Context) {
req := &LogoutReq{}
if err := c.ShouldBindJSON(req); err != nil {
httpresp.JsonBadRequest(c)
return
}
if req.RefreshToken == "" {
cookie, err := c.Cookie("refresh_token")
if err != nil {
httpresp.JsonUnauthorized(c)
return
}
req.RefreshToken = cookie
}
if err := sessionLogout(c, req.RefreshToken); err != nil {
log.Errorf("Logout sessionLogout error: %v", err)
}
httpresp.JsonOK(c, httpresp.Success(&LogoutResp{}))
}

View File

@@ -0,0 +1,156 @@
package httphandler
import (
"bou.ke/monkey"
"fmt"
"git.hlsq.asia/alex/service-common/net/grpc/grpcclient"
"git.hlsq.asia/alex/service-common/net/http/httpresp"
"git.hlsq.asia/alex/service-common/proto/rs/rspb"
"git.hlsq.asia/alex/service-common/proto/rs/rspb/mocks"
"git.hlsq.asia/alex/service-common/utils"
"git.hlsq.asia/alex/service-gateway/internal/testutil"
"github.com/gin-gonic/gin"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
"net/http"
"testing"
)
type LoginTestSuite struct {
testutil.TestSuite
}
func (ts *LoginTestSuite) TestLogin() {
gin.SetMode(gin.TestMode)
ts.Run("ShouldBindJSON Failed", func() {
w, c := utils.CreateTestContext("POST", "/", &LoginReq{
Phone: "",
Code: "",
})
Login(c)
utils.AssertResponse(&ts.Suite, w, http.StatusBadRequest, httpresp.ParamError)
})
ts.Run("UserNewClientLB Failed", func() {
monkey.Patch(grpcclient.UserNewClientLB, func() (rspb.UserClient, error) {
return nil, assert.AnError
})
defer monkey.Unpatch(grpcclient.UserNewClientLB)
w, c := utils.CreateTestContext("POST", "/", &LoginReq{
Phone: "13800000000",
Code: "1234",
})
Login(c)
utils.AssertResponse(&ts.Suite, w, http.StatusOK, httpresp.Failed)
})
ts.Run("Login Failed", func() {
ctrl := gomock.NewController(ts.T())
defer ctrl.Finish()
client := mocks.NewMockUserClient(ctrl)
client.EXPECT().
PhoneLogin(gomock.Any(), gomock.Any()).
Return(nil, fmt.Errorf("gRPC failed"))
monkey.Patch(grpcclient.UserNewClientLB, func() (rspb.UserClient, error) {
return client, nil
})
defer monkey.Unpatch(grpcclient.UserNewClientLB)
w, c := utils.CreateTestContext("POST", "/", &LoginReq{
Phone: "13800000000",
Code: "1234",
})
Login(c)
utils.AssertResponse(&ts.Suite, w, http.StatusOK, httpresp.Failed)
})
ts.Run("OK", func() {
ctrl := gomock.NewController(ts.T())
defer ctrl.Finish()
client := mocks.NewMockUserClient(ctrl)
client.EXPECT().
PhoneLogin(gomock.Any(), gomock.Any()).
Return(&rspb.PhoneLoginResp{USN: 1, Name: "hh"}, nil)
monkey.Patch(grpcclient.UserNewClientLB, func() (rspb.UserClient, error) {
return client, nil
})
defer monkey.Unpatch(grpcclient.UserNewClientLB)
w, c := utils.CreateTestContext("POST", "/", &LoginReq{
Phone: "13800000000",
Code: "1234",
})
Login(c)
utils.AssertResponse(&ts.Suite, w, http.StatusOK, httpresp.OK)
})
}
func (ts *LoginTestSuite) TestRefreshToken() {
gin.SetMode(gin.TestMode)
ts.Run("ShouldBindJSON Failed", func() {
w, c := utils.CreateTestContext("POST", "/", &RefreshTokenReq{
RefreshToken: "",
})
RefreshToken(c)
utils.AssertResponse(&ts.Suite, w, http.StatusBadRequest, httpresp.ParamError)
})
ts.Run("ParseToken Failed", func() {
monkey.Patch(utils.ParseToken, func(tokenString string, secret string) (*utils.Claims, error) {
return nil, assert.AnError
})
defer monkey.Unpatch(utils.ParseToken)
w, c := utils.CreateTestContext("POST", "/", &RefreshTokenReq{
RefreshToken: "abc",
})
RefreshToken(c)
utils.AssertResponse(&ts.Suite, w, http.StatusOK, httpresp.TokenInvalid)
})
//ts.Run("Redis Get Failed", func() {
// monkey.Patch(utils.ParseToken, func(tokenString string, secret string) (*utils.Claims, error) {
// if tokenString == "abc" {
// return &utils.Claims{USN: 1}, nil
// }
// return nil, assert.AnError
// })
// defer monkey.Unpatch(utils.ParseToken)
//
// redis.GetClient().Set(context.Background(), global.KeyGatewayRefreshToken+1, "ab", redis2.KeepTTL)
//
// w, c := utils.CreateTestContext("POST", "/", &RefreshTokenReq{
// RefreshToken: "abc",
// })
// RefreshToken(c)
// utils.AssertResponse(&ts.Suite, w, http.StatusOK, http_resp.TokenInvalid)
//})
//
//ts.Run("OK", func() {
// monkey.Patch(utils.ParseToken, func(tokenString string, secret string) (*utils.Claims, error) {
// if tokenString == "abc" {
// return &utils.Claims{USN: 1}, nil
// }
// return nil, assert.AnError
// })
// defer monkey.Unpatch(utils.ParseToken)
//
// redis.GetClient().Set(context.Background(), fmt.Sprintf(global.KeyGatewayRefreshToken, 1), "abc", redis2.KeepTTL)
//
// w, c := utils.CreateTestContext("POST", "/", &RefreshTokenReq{
// RefreshToken: "abc",
// })
// RefreshToken(c)
// utils.AssertResponse(&ts.Suite, w, http.StatusOK, http_resp.OK)
//})
}
func TestLoginTestSuite(t *testing.T) {
suite.Run(t, &LoginTestSuite{})
}

View File

@@ -0,0 +1,108 @@
package httphandler
import (
"git.hlsq.asia/alex/service-common/db/redis"
"git.hlsq.asia/alex/service-common/utils"
"git.hlsq.asia/alex/service-gateway/config"
"git.hlsq.asia/alex/service-gateway/internal/global"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
var (
scriptLoginSha1 string
scriptLogin = `
local at_key = KEYS[1] .. ARGV[1]
local rt_key = KEYS[2] .. ARGV[2]
local session_key = KEYS[3] .. ARGV[3]
redis.call("HSET", at_key,
"usn", ARGV[3],
"ip", ARGV[6],
"ua", ARGV[7],
"rt", ARGV[2]
)
redis.call("EXPIRE", at_key, tonumber(ARGV[4]))
redis.call("HSET", rt_key,
"usn", ARGV[3],
"ip", ARGV[6],
"ua", ARGV[7],
"at", ARGV[1]
)
redis.call("EXPIRE", rt_key, tonumber(ARGV[5]))
local all_rts = redis.call("SMEMBERS", session_key)
-- 只允许最大10个会话,多了的随机踢掉
if #all_rts >= 10 then
local rk = KEYS[2] .. all_rts[1]
local ak = KEYS[1] .. redis.call("HGET", rk, "at")
redis.call("DEL", rk)
redis.call("DEL", ak)
end
-- 清理已经失效的会话
for i, rt in ipairs(all_rts) do
if redis.call("EXISTS", KEYS[2] .. rt) == 0 then
redis.call("SREM", session_key, rt)
end
end
redis.call("SADD", session_key, ARGV[2])
redis.call("EXPIRE", session_key, tonumber(ARGV[5]) + 600)
return 1
`
)
func sessionLogin(c *gin.Context, usn int64) (string, string, error) {
if scriptLoginSha1 == "" {
scriptLoginSha1 = redis.GetClient().ScriptLoad(c, scriptLogin).Val()
}
at := uuid.New().String()
rt := uuid.New().String()
err := redis.GetClient().EvalSha(
c, scriptLoginSha1,
[]string{global.KeyGatewayAccessToken, global.KeyGatewayRefreshToken, global.KeyGatewaySession},
at,
rt,
usn,
config.Get().Auth.ShortExpire,
config.Get().Auth.LongExpire,
c.RemoteIP(),
c.GetHeader("User-Agent"),
).Err()
if err != nil {
return "", "", utils.ErrorsWrap(err)
}
c.SetCookie("refresh_token", rt, int(config.Get().Auth.LongExpire), "/", ".hlsq.asia", true, true)
return at, rt, nil
}
var (
scriptLogoutSha1 string
scriptLogout = `
local rt_key = KEYS[2] .. ARGV[1]
local usn = redis.call("HGET", rt_key, "usn")
local at = redis.call("HGET", rt_key, "at")
local at_key = KEYS[1] .. at
local session_key = KEYS[3] .. usn
redis.call("DEL", at_key)
redis.call("DEL", rt_key)
redis.call("SREM", session_key, ARGV[1])
return 1
`
)
func sessionLogout(c *gin.Context, rt string) error {
if scriptLogoutSha1 == "" {
scriptLogoutSha1 = redis.GetClient().ScriptLoad(c, scriptLogout).Val()
}
return redis.GetClient().EvalSha(
c, scriptLogoutSha1,
[]string{global.KeyGatewayAccessToken, global.KeyGatewayRefreshToken, global.KeyGatewaySession},
rt,
).Err()
}

View File

@@ -3,10 +3,10 @@ package client
import ( import (
"context" "context"
"fmt" "fmt"
"git.hlsq.asia/mmorpg/service-common/db/redis" "git.hlsq.asia/alex/service-common/db/redis"
"git.hlsq.asia/mmorpg/service-common/log" "git.hlsq.asia/alex/service-common/log"
"git.hlsq.asia/mmorpg/service-common/net/socket" "git.hlsq.asia/alex/service-common/net/socket"
"git.hlsq.asia/mmorpg/service-gateway/internal/global" "git.hlsq.asia/alex/service-gateway/internal/global"
"go.uber.org/zap" "go.uber.org/zap"
"runtime/debug" "runtime/debug"
"sync" "sync"
@@ -22,18 +22,17 @@ type Client struct {
cancel context.CancelFunc // 取消上下文 cancel context.CancelFunc // 取消上下文
heartBeat time.Time // 最后一次心跳 heartBeat time.Time // 最后一次心跳
Status int32 // 状态:0 登陆中 1 正常 2 离线 Status int32 // 状态:0 登陆中 1 正常 2 离线
USN string // 用户ID USN int64 // 用户ID
SceneSID string // 场景服ID SceneSID int64 // 场景服ID
InstanceID int32 // 副本ID,副本类型 InstanceID int32 // 副本ID,副本类型
UniqueNo string // 副本唯一编号 UniqueNo int64 // 副本唯一编号
} }
func NewClient(usn string, conn socket.ISocketConn) *Client { func NewClient(conn socket.ISocketConn) *Client {
client := &Client{ client := &Client{
USN: usn,
conn: conn, conn: conn,
logger: log.GetLogger().Named(fmt.Sprintf("usn:%v", usn)), logger: log.GetLogger(),
heartBeat: time.Now(), heartBeat: time.Now(),
mailChan: make(chan Event, 1024), mailChan: make(chan Event, 1024),
} }
@@ -43,6 +42,11 @@ func NewClient(usn string, conn socket.ISocketConn) *Client {
return client return client
} }
func (c *Client) SetUSN(usn int64) {
c.USN = usn
c.logger = log.GetLogger().Named(fmt.Sprintf("usn:%v", usn))
}
func (c *Client) Loop() { func (c *Client) Loop() {
defer func() { defer func() {
if err := recover(); err != nil { if err := recover(); err != nil {

View File

@@ -3,11 +3,11 @@ package client
import ( import (
"context" "context"
"fmt" "fmt"
"git.hlsq.asia/mmorpg/service-common/db/redis" "git.hlsq.asia/alex/service-common/db/redis"
"git.hlsq.asia/mmorpg/service-common/net/grpc/grpc_client" "git.hlsq.asia/alex/service-common/net/grpc/grpcclient"
"git.hlsq.asia/mmorpg/service-common/proto/rs/grpc_pb" "git.hlsq.asia/alex/service-common/proto/rs/rspb"
"git.hlsq.asia/mmorpg/service-common/proto/ss/ss_pb" "git.hlsq.asia/alex/service-common/proto/ss/sspb"
"git.hlsq.asia/mmorpg/service-gateway/internal/global" "git.hlsq.asia/alex/service-gateway/internal/global"
"google.golang.org/protobuf/proto" "google.golang.org/protobuf/proto"
"time" "time"
) )
@@ -15,23 +15,23 @@ import (
func (c *Client) handle(event Event) { func (c *Client) handle(event Event) {
switch e := event.(type) { switch e := event.(type) {
case *ClientEvent: case *ClientEvent:
msg := &ss_pb.Message{} msg := &sspb.Message{}
if err := proto.Unmarshal(e.Msg, msg); err != nil { if err := proto.Unmarshal(e.Msg, msg); err != nil {
c.logger.Errorf("handle event proto.Unmarshal err: %v", err) c.logger.Errorf("handle event proto.Unmarshal err: %v", err)
c.cancel() c.cancel()
return return
} }
switch msg.ID { switch msg.ID {
case ss_pb.MessageID_MESSAGE_ID_ENTER_INSTANCE: case sspb.MessageID_MESSAGE_ID_ENTER_INSTANCE:
m := &ss_pb.C2S_EnterInstance{} m := &sspb.C2S_EnterInstance{}
if err := proto.Unmarshal(msg.Payload, m); err != nil { if err := proto.Unmarshal(msg.Payload, m); err != nil {
c.logger.Errorf("handle event proto.Unmarshal err: %v", err) c.logger.Errorf("handle event proto.Unmarshal err: %v", err)
c.cancel() c.cancel()
return return
} }
c.onEnter(m) c.onEnter(m)
case ss_pb.MessageID_MESSAGE_ID_ACTION: case sspb.MessageID_MESSAGE_ID_ACTION:
m := &ss_pb.C2S_Action{} m := &sspb.C2S_Action{}
if err := proto.Unmarshal(msg.Payload, m); err != nil { if err := proto.Unmarshal(msg.Payload, m); err != nil {
c.logger.Errorf("handle event proto.Unmarshal err: %v", err) c.logger.Errorf("handle event proto.Unmarshal err: %v", err)
c.cancel() c.cancel()
@@ -46,20 +46,20 @@ func (c *Client) handle(event Event) {
c.Status = 1 c.Status = 1
UserMgr.Add(c.USN, c) UserMgr.Add(c.USN, c)
redis.GetClient().HSet(c.ctx, fmt.Sprintf(global.KeyGatewayInfo, c.USN), global.HFieldInfoGatewaySID, global.GatewaySID) redis.GetClient().HSet(c.ctx, fmt.Sprintf(global.KeyGatewayInfo, c.USN), global.HFieldInfoGatewaySID, global.GatewaySID)
c.WriteMessage(ss_pb.MessageID_MESSAGE_ID_LOGIN_SUCCESS, &ss_pb.S2C_LoginSuccess{ c.WriteMessage(sspb.MessageID_MESSAGE_ID_LOGIN_SUCCESS, &sspb.S2C_LoginSuccess{
InstanceID: 1, InstanceID: 1,
}) })
} }
} }
} }
func (c *Client) onEnter(msg *ss_pb.C2S_EnterInstance) { func (c *Client) onEnter(msg *sspb.C2S_EnterInstance) {
client, err := grpc_client.SceneNewClientLB() client, err := grpcclient.SceneNewClientLB()
if err != nil { if err != nil {
c.logger.Errorf("SceneNewClient err: %v", err) c.logger.Errorf("SceneNewClient err: %v", err)
return return
} }
resp, err := client.Enter(c.ctx, &grpc_pb.EnterReq{ resp, err := client.Enter(c.ctx, &rspb.EnterReq{
USN: c.USN, USN: c.USN,
GatewaySID: global.GatewaySID, GatewaySID: global.GatewaySID,
InstanceID: msg.InstanceID, InstanceID: msg.InstanceID,
@@ -71,19 +71,19 @@ func (c *Client) onEnter(msg *ss_pb.C2S_EnterInstance) {
c.SceneSID = resp.SceneSID c.SceneSID = resp.SceneSID
c.UniqueNo = resp.UniqueNo c.UniqueNo = resp.UniqueNo
c.InstanceID = msg.InstanceID c.InstanceID = msg.InstanceID
c.WriteBytes(ss_pb.MessageID(resp.MessageID), resp.Payload) c.WriteBytes(sspb.MessageID(resp.MessageID), resp.Payload)
} }
func (c *Client) onLeave() { func (c *Client) onLeave() {
if c.SceneSID == "" { if c.SceneSID == 0 {
return return
} }
client, err := grpc_client.SceneNewClient(c.SceneSID) client, err := grpcclient.SceneNewClient(c.SceneSID)
if err != nil { if err != nil {
c.logger.Errorf("SceneNewClient err: %v", err) c.logger.Errorf("SceneNewClient err: %v", err)
return return
} }
_, err = client.Leave(context.Background(), &grpc_pb.LeaveReq{ _, err = client.Leave(context.Background(), &rspb.LeaveReq{
USN: c.USN, USN: c.USN,
UniqueNo: c.UniqueNo, UniqueNo: c.UniqueNo,
}) })
@@ -93,11 +93,11 @@ func (c *Client) onLeave() {
} }
} }
func (c *Client) onAction(msg *ss_pb.C2S_Action) { func (c *Client) onAction(msg *sspb.C2S_Action) {
if c.SceneSID == "" { if c.SceneSID == 0 {
return return
} }
if err := grpc_client.SendMessageToScene(c.SceneSID, grpc_client.FunAction, &grpc_pb.ActionReq{ if err := grpcclient.SendMessageToScene(c.SceneSID, grpcclient.FunAction, &rspb.ActionReq{
UniqueNo: c.UniqueNo, UniqueNo: c.UniqueNo,
USN: c.USN, USN: c.USN,
Action: int32(msg.Action), Action: int32(msg.Action),

View File

@@ -1,12 +1,12 @@
package client package client
import ( import (
"git.hlsq.asia/mmorpg/service-common/proto/ss/ss_pb" "git.hlsq.asia/alex/service-common/proto/ss/sspb"
"google.golang.org/protobuf/proto" "google.golang.org/protobuf/proto"
) )
// WriteMessage 向客户端发送消息 // WriteMessage 向客户端发送消息
func (c *Client) WriteMessage(id ss_pb.MessageID, data proto.Message) { func (c *Client) WriteMessage(id sspb.MessageID, data proto.Message) {
if c.conn == nil || c.conn.IsClose() { if c.conn == nil || c.conn.IsClose() {
return return
} }
@@ -15,7 +15,7 @@ func (c *Client) WriteMessage(id ss_pb.MessageID, data proto.Message) {
c.logger.Errorf("WriteMessage proto.Marshal err: %v", err) c.logger.Errorf("WriteMessage proto.Marshal err: %v", err)
return return
} }
m, err := proto.Marshal(&ss_pb.Message{ m, err := proto.Marshal(&sspb.Message{
ID: id, ID: id,
Payload: d, Payload: d,
}) })
@@ -29,11 +29,11 @@ func (c *Client) WriteMessage(id ss_pb.MessageID, data proto.Message) {
} }
// WriteBytes 向客户端发送字节数据 // WriteBytes 向客户端发送字节数据
func (c *Client) WriteBytes(id ss_pb.MessageID, data []byte) { func (c *Client) WriteBytes(id sspb.MessageID, data []byte) {
if c.conn == nil || c.conn.IsClose() { if c.conn == nil || c.conn.IsClose() {
return return
} }
m, err := proto.Marshal(&ss_pb.Message{ m, err := proto.Marshal(&sspb.Message{
ID: id, ID: id,
Payload: data, Payload: data,
}) })

View File

@@ -1,42 +1,42 @@
package client package client
import ( import (
"git.hlsq.asia/mmorpg/service-gateway/internal/global" "git.hlsq.asia/alex/service-gateway/internal/global"
"sync" "sync"
) )
var UserMgr *userManager var UserMgr *userManager
type userManager struct { type userManager struct {
userMap map[string]*Client userMap map[int64]*Client
sync.RWMutex sync.RWMutex
} }
func init() { func init() {
UserMgr = &userManager{ UserMgr = &userManager{
userMap: make(map[string]*Client), userMap: make(map[int64]*Client),
} }
} }
func (m *userManager) Add(usn string, client *Client) { func (m *userManager) Add(usn int64, client *Client) {
m.Lock() m.Lock()
defer m.Unlock() defer m.Unlock()
m.userMap[usn] = client m.userMap[usn] = client
global.OnlineUsersGauge.Inc() global.OnlineUsersGauge.Inc()
} }
func (m *userManager) Delete(usn string) { func (m *userManager) Delete(usn int64) {
m.Lock() m.Lock()
defer m.Unlock() defer m.Unlock()
delete(m.userMap, usn) delete(m.userMap, usn)
global.OnlineUsersGauge.Dec() global.OnlineUsersGauge.Dec()
} }
func (m *userManager) GetAll() map[string]*Client { func (m *userManager) GetAll() map[int64]*Client {
m.RLock() m.RLock()
defer m.RUnlock() defer m.RUnlock()
copyMap := make(map[string]*Client, len(m.userMap)) copyMap := make(map[int64]*Client, len(m.userMap))
for k, v := range m.userMap { for k, v := range m.userMap {
copyMap[k] = v copyMap[k] = v
} }
@@ -54,7 +54,7 @@ func (m *userManager) GetAllInterface() []interface{} {
return r return r
} }
func (m *userManager) GetByUSN(usn string) *Client { func (m *userManager) GetByUSN(usn int64) *Client {
m.RLock() m.RLock()
defer m.RUnlock() defer m.RUnlock()
return m.userMap[usn] return m.userMap[usn]

View File

@@ -3,13 +3,14 @@ package login
import ( import (
"context" "context"
"fmt" "fmt"
"git.hlsq.asia/mmorpg/service-common/db/redis" "git.hlsq.asia/alex/service-common/db/redis"
"git.hlsq.asia/mmorpg/service-common/log" "git.hlsq.asia/alex/service-common/log"
"git.hlsq.asia/mmorpg/service-common/net/grpc/grpc_client" "git.hlsq.asia/alex/service-common/net/grpc/grpcclient"
"git.hlsq.asia/mmorpg/service-common/proto/rs/grpc_pb" "git.hlsq.asia/alex/service-common/proto/rs/rspb"
"git.hlsq.asia/mmorpg/service-common/proto/ss/ss_pb" "git.hlsq.asia/alex/service-common/proto/ss/sspb"
"git.hlsq.asia/mmorpg/service-gateway/internal/global" "git.hlsq.asia/alex/service-common/utils"
"git.hlsq.asia/mmorpg/service-gateway/internal/handler/ws_handler/client" "git.hlsq.asia/alex/service-gateway/internal/global"
"git.hlsq.asia/alex/service-gateway/internal/handler/wshandler/client"
"sync" "sync"
"time" "time"
) )
@@ -108,8 +109,8 @@ func (l *Login) Stop() {
// StartLogin 开始登录流程 // StartLogin 开始登录流程
func (l *Login) StartLogin(user *User) { func (l *Login) StartLogin(user *User) {
if !l.CheckToken(user) { if !l.CheckToken(user) {
user.Cli.WriteMessage(ss_pb.MessageID_MESSAGE_ID_KICK_OUT, &ss_pb.S2C_KickOut{ user.Cli.WriteMessage(sspb.MessageID_MESSAGE_ID_KICK_OUT, &sspb.S2C_KickOut{
ID: ss_pb.KickOutID_KICK_OUT_ID_TOKEN_INVALID, ID: sspb.KickOutID_KICK_OUT_ID_TOKEN_INVALID,
}) })
user.Cli.CloseClient() user.Cli.CloseClient()
return return
@@ -117,8 +118,8 @@ func (l *Login) StartLogin(user *User) {
if gatewaySID := l.CheckOnline(user); len(gatewaySID) > 0 { if gatewaySID := l.CheckOnline(user); len(gatewaySID) > 0 {
// 如果在线就要踢,如果踢失败了就返回服务器繁忙,一般不应该走到这里 // 如果在线就要踢,如果踢失败了就返回服务器繁忙,一般不应该走到这里
if !l.KickUser(user.Cli.SceneSID, user.Cli.USN) { if !l.KickUser(user.Cli.SceneSID, user.Cli.USN) {
user.Cli.WriteMessage(ss_pb.MessageID_MESSAGE_ID_KICK_OUT, &ss_pb.S2C_KickOut{ user.Cli.WriteMessage(sspb.MessageID_MESSAGE_ID_KICK_OUT, &sspb.S2C_KickOut{
ID: ss_pb.KickOutID_KICK_OUT_ID_SERVER_BUSY, ID: sspb.KickOutID_KICK_OUT_ID_SERVER_BUSY,
}) })
user.Cli.CloseClient() user.Cli.CloseClient()
return return
@@ -127,8 +128,8 @@ func (l *Login) StartLogin(user *User) {
if client.UserMgr.GetSize() >= global.MaxOnlineSize { if client.UserMgr.GetSize() >= global.MaxOnlineSize {
// 如果人数满了就排队 // 如果人数满了就排队
if err := GetQueueUp().Enqueue(user.Cli); err != nil { if err := GetQueueUp().Enqueue(user.Cli); err != nil {
user.Cli.WriteMessage(ss_pb.MessageID_MESSAGE_ID_KICK_OUT, &ss_pb.S2C_KickOut{ user.Cli.WriteMessage(sspb.MessageID_MESSAGE_ID_KICK_OUT, &sspb.S2C_KickOut{
ID: ss_pb.KickOutID_KICK_OUT_ID_QUEUE_UP_FULL, ID: sspb.KickOutID_KICK_OUT_ID_QUEUE_UP_FULL,
}) })
user.Cli.CloseClient() user.Cli.CloseClient()
return return
@@ -136,13 +137,13 @@ func (l *Login) StartLogin(user *User) {
// 告诉客户端正在排队 // 告诉客户端正在排队
position, ok := GetQueueUp().GetPosition(user.Cli.USN) position, ok := GetQueueUp().GetPosition(user.Cli.USN)
if !ok { if !ok {
user.Cli.WriteMessage(ss_pb.MessageID_MESSAGE_ID_KICK_OUT, &ss_pb.S2C_KickOut{ user.Cli.WriteMessage(sspb.MessageID_MESSAGE_ID_KICK_OUT, &sspb.S2C_KickOut{
ID: ss_pb.KickOutID_KICK_OUT_ID_SERVER_BUSY, ID: sspb.KickOutID_KICK_OUT_ID_SERVER_BUSY,
}) })
user.Cli.CloseClient() user.Cli.CloseClient()
return return
} }
user.Cli.WriteMessage(ss_pb.MessageID_MESSAGE_ID_QUEUE_UP, &ss_pb.S2C_QueueUp{ user.Cli.WriteMessage(sspb.MessageID_MESSAGE_ID_QUEUE_UP, &sspb.S2C_QueueUp{
QueueUpCount: int32(position), QueueUpCount: int32(position),
}) })
} else { } else {
@@ -152,7 +153,9 @@ func (l *Login) StartLogin(user *User) {
// CheckToken 校验Token是否有效 // CheckToken 校验Token是否有效
func (l *Login) CheckToken(user *User) bool { func (l *Login) CheckToken(user *User) bool {
return redis.GetClient().Get(l.ctx, fmt.Sprintf(global.KeyGatewayAccessToken, user.Cli.USN)).Val() == user.Token usn, _ := redis.GetClient().HGet(context.Background(), global.KeyGatewayAccessToken+user.Token, (&utils.UserSession{}).GetUsnKey()).Int64()
user.Cli.SetUSN(usn)
return usn > 0
} }
// CheckOnline 校验是否在线 // CheckOnline 校验是否在线
@@ -161,13 +164,13 @@ func (l *Login) CheckOnline(user *User) string {
} }
// KickUser 把玩家踢下线 // KickUser 把玩家踢下线
func (l *Login) KickUser(gatewaySID string, usn string) bool { func (l *Login) KickUser(gatewaySID int64, usn int64) bool {
gc, err := grpc_client.GatewayNewClient(gatewaySID) gc, err := grpcclient.GatewayNewClient(gatewaySID)
if err != nil { if err != nil {
log.Errorf("KickUser cannot find gateway client: %v, sid: %v", err, gatewaySID) log.Errorf("KickUser cannot find gateway client: %v, sid: %v", err, gatewaySID)
return false return false
} }
_, err = gc.KickUser(l.ctx, &grpc_pb.KickUserReq{USN: usn}) _, err = gc.KickUser(l.ctx, &rspb.KickUserReq{USN: usn})
if err != nil { if err != nil {
log.Errorf("KickUser err: %v, sid: %v, usn: %v", err, gatewaySID, usn) log.Errorf("KickUser err: %v, sid: %v, usn: %v", err, gatewaySID, usn)
return false return false

View File

@@ -3,7 +3,7 @@ package login
import ( import (
"context" "context"
"errors" "errors"
"git.hlsq.asia/mmorpg/service-gateway/internal/handler/ws_handler/client" "git.hlsq.asia/alex/service-gateway/internal/handler/wshandler/client"
"sync" "sync"
"sync/atomic" "sync/atomic"
) )
@@ -78,7 +78,7 @@ func (q *QueueUp) Dequeue() (*client.Client, error) {
} }
// GetPosition 返回用户前面还有多少人在排队 // GetPosition 返回用户前面还有多少人在排队
func (q *QueueUp) GetPosition(usn string) (int64, bool) { func (q *QueueUp) GetPosition(usn int64) (int64, bool) {
val, ok := q.waiting.Load(usn) val, ok := q.waiting.Load(usn)
if !ok { if !ok {
return 0, false return 0, false
@@ -88,7 +88,7 @@ func (q *QueueUp) GetPosition(usn string) (int64, bool) {
} }
// RemoveUser 安全移除用户(标记为取消) // RemoveUser 安全移除用户(标记为取消)
func (q *QueueUp) RemoveUser(usn string) bool { func (q *QueueUp) RemoveUser(usn int64) bool {
_, loaded := q.waiting.LoadAndDelete(usn) _, loaded := q.waiting.LoadAndDelete(usn)
return loaded return loaded
} }

View File

@@ -1,10 +1,11 @@
package http_gateway package httpgateway
import ( import (
"fmt" "fmt"
"git.hlsq.asia/mmorpg/service-common/net/http/http_resp" "git.hlsq.asia/alex/service-common/db/redis"
"git.hlsq.asia/mmorpg/service-common/utils" "git.hlsq.asia/alex/service-common/net/http/httpresp"
"git.hlsq.asia/mmorpg/service-gateway/config" "git.hlsq.asia/alex/service-common/utils"
"git.hlsq.asia/alex/service-gateway/internal/global"
"github.com/gin-contrib/cors" "github.com/gin-contrib/cors"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"go.uber.org/zap" "go.uber.org/zap"
@@ -46,7 +47,7 @@ func authJwt() gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
pList := strings.SplitN(c.Request.URL.Path, "/", 4) pList := strings.SplitN(c.Request.URL.Path, "/", 4)
if len(pList) < 4 || pList[2] == "" { if len(pList) < 4 || pList[2] == "" {
http_resp.JsonNotFound(c) httpresp.JsonNotFound(c)
c.Abort() c.Abort()
return return
} }
@@ -59,21 +60,22 @@ func authJwt() gin.HandlerFunc {
c.Next() c.Next()
return return
} }
http_resp.JsonUnauthorized(c) httpresp.JsonUnauthorized(c)
c.Abort() c.Abort()
return return
} }
claims, err := utils.ParseToken(token, config.Get().Auth.Secret)
if err != nil { usn, _ := redis.GetClient().HGet(c, global.KeyGatewayAccessToken+token, (&utils.UserSession{}).GetUsnKey()).Int64()
http_resp.JsonUnauthorized(c) if usn == 0 {
httpresp.JsonUnauthorized(c)
c.Abort() c.Abort()
return return
} }
// 这里将Header写到请求中,grpc-gateway框架会读取然后传给grpc服务 // 这里将Header写到请求中,grpc-gateway框架会读取然后传给grpc服务
c.Request.Header.Set("X-Usn", claims.USN) c.Request.Header.Set("X-Usn", utils.Int64ToString(usn))
// 这里写到上下文中,打日志 // 这里写到上下文中,打日志
c.Set("usn", claims.USN) c.Set("usn", usn)
c.Next() c.Next()
} }
} }

View File

@@ -1,19 +1,20 @@
package http_gateway package httpgateway
import ( import (
"context" "context"
"git.hlsq.asia/mmorpg/service-common/discover/common" "git.hlsq.asia/alex/service-common/discover/common"
"git.hlsq.asia/mmorpg/service-common/log" "git.hlsq.asia/alex/service-common/log"
"git.hlsq.asia/mmorpg/service-common/net/grpc/grpc_client" "git.hlsq.asia/alex/service-common/net/grpc/grpcclient"
"git.hlsq.asia/mmorpg/service-common/net/http/http_resp" "git.hlsq.asia/alex/service-common/net/http/httpresp"
"git.hlsq.asia/mmorpg/service-common/proto/rs/grpc_pb" "git.hlsq.asia/alex/service-common/proto/rs/rspb"
"git.hlsq.asia/mmorpg/service-gateway/internal/handler/http_handler" "git.hlsq.asia/alex/service-gateway/internal/handler/httphandler"
"git.hlsq.asia/mmorpg/service-gateway/internal/net/http_gateway/wrapper" "git.hlsq.asia/alex/service-gateway/internal/net/httpgateway/wrapper"
"github.com/gin-contrib/cors" "github.com/gin-contrib/cors"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin" "go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
"google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/encoding/protojson"
"strings"
) )
func InitServeMux() *runtime.ServeMux { func InitServeMux() *runtime.ServeMux {
@@ -49,16 +50,22 @@ func InitRouter() *gin.Engine {
gin.Recovery(), gin.Recovery(),
ginLogger(log.GetLogger().Named("GIN")), ginLogger(log.GetLogger().Named("GIN")),
cors.New(corsConfig()), cors.New(corsConfig()),
otelgin.Middleware(common.KeyDiscoverServiceNameGateway), otelgin.Middleware(
common.KeyDiscoverServiceNameGateway,
otelgin.WithSpanNameFormatter(func(c *gin.Context) string {
method := strings.ToUpper(c.Request.Method)
return method + " " + c.Request.URL.Path
}),
),
) )
r.HandleMethodNotAllowed = true r.HandleMethodNotAllowed = true
r.NoMethod(func(c *gin.Context) { r.NoMethod(func(c *gin.Context) {
http_resp.JsonMethodNotAllowed(c) httpresp.JsonMethodNotAllowed(c)
c.Abort() c.Abort()
}) })
r.NoRoute(func(c *gin.Context) { r.NoRoute(func(c *gin.Context) {
http_resp.JsonNotFound(c) httpresp.JsonNotFound(c)
c.Abort() c.Abort()
}) })
@@ -66,7 +73,7 @@ func InitRouter() *gin.Engine {
auth.Use(authJwt()) auth.Use(authJwt())
// 网关 // 网关
initBaseRoute(auth) initGatewayPath(auth)
// 用户中心 // 用户中心
initUserPath(auth) initUserPath(auth)
// 奇怪的知识-服务端 // 奇怪的知识-服务端
@@ -75,22 +82,25 @@ func InitRouter() *gin.Engine {
return r return r
} }
func initBaseRoute(r *gin.RouterGroup) { func initGatewayPath(r *gin.RouterGroup) {
g := r.Group("/gw") g := r.Group("/" + common.KeyDiscoverServiceNameGateway)
g.POST("/open/login", http_handler.Login)
g.POST("/open/refresh_token", http_handler.RefreshToken) g.POST("/open/login", httphandler.Login)
g.POST("/open/refresh_token", httphandler.RefreshToken)
g.POST("/open/logout", httphandler.Logout)
} }
func initUserPath(r *gin.RouterGroup) { func initUserPath(r *gin.RouterGroup) {
g := r.Group("/user") g := r.Group("/" + common.KeyDiscoverServiceNameUser)
client, err := grpc_client.UserNewClientLB()
client, err := grpcclient.UserNewClientLB()
if err != nil { if err != nil {
log.Errorf("get user conn failed: %v", err) log.Errorf("get user conn failed: %v", err)
return return
} }
gwMux := InitServeMux() gwMux := InitServeMux()
if err = grpc_pb.RegisterUserHandlerClient(context.Background(), gwMux, client); err != nil { if err = rspb.RegisterUserHandlerClient(context.Background(), gwMux, client); err != nil {
log.Errorf("RegisterUserHandlerClient err: %v", err) log.Errorf("RegisterUserHandlerClient err: %v", err)
return return
} }
@@ -99,15 +109,16 @@ func initUserPath(r *gin.RouterGroup) {
} }
func initQgdzsPath(r *gin.RouterGroup) { func initQgdzsPath(r *gin.RouterGroup) {
g := r.Group("/qgdzs") g := r.Group("/" + common.KeyDiscoverServiceNameQgdzs)
client, err := grpc_client.QgdzsNewClientLB()
client, err := grpcclient.QgdzsNewClientLB()
if err != nil { if err != nil {
log.Errorf("get qgdzs conn failed: %v", err) log.Errorf("get qgdzs conn failed: %v", err)
return return
} }
gwMux := InitServeMux() gwMux := InitServeMux()
if err = grpc_pb.RegisterQgdzsHandlerClient(context.Background(), gwMux, client); err != nil { if err = rspb.RegisterQgdzsHandlerClient(context.Background(), gwMux, client); err != nil {
log.Errorf("RegisterQgdzsHandlerClient err: %v", err) log.Errorf("RegisterQgdzsHandlerClient err: %v", err)
return return
} }

View File

@@ -3,8 +3,8 @@ package wrapper
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"git.hlsq.asia/mmorpg/service-common/net/http/http_resp" "git.hlsq.asia/alex/service-common/net/http/httpresp"
"git.hlsq.asia/mmorpg/service-common/proto/rs/rs_common" "git.hlsq.asia/alex/service-common/proto/rs/rscommon"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
"google.golang.org/grpc/status" "google.golang.org/grpc/status"
@@ -17,32 +17,32 @@ func ErrorHandler(_ context.Context, _ *runtime.ServeMux, _ runtime.Marshaler, w
if !ok { if !ok {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(http_resp.Error(http_resp.Failed)) _ = json.NewEncoder(w).Encode(httpresp.Error(httpresp.Failed))
return return
} }
code, msg := 0, "" code, msg := 0, ""
for _, detail := range st.Details() { for _, detail := range st.Details() {
if errorInfo, ok := detail.(*rs_common.ErrorInfo); ok { if errorInfo, ok := detail.(*rscommon.ErrorInfo); ok {
code = int(errorInfo.Code) code = int(errorInfo.Code)
msg = errorInfo.Msg msg = errorInfo.Msg
break break
} }
} }
if code == 0 { if code == 0 {
code = http_resp.Failed.Code() code = httpresp.Failed.Code()
msg = http_resp.Failed.Error() msg = httpresp.Failed.Error()
} }
if st.Code() == codes.Unknown || st.Code() == codes.Unimplemented || st.Code() == codes.NotFound { if st.Code() == codes.Unknown || st.Code() == codes.Unimplemented || st.Code() == codes.NotFound {
msg = st.Message() msg = st.Message()
} }
if st.Code() == codes.NotFound { if st.Code() == codes.NotFound {
code = http_resp.NotFound.Code() code = httpresp.NotFound.Code()
} }
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
w.WriteHeader(grpcCodeToHTTPCode(st.Code())) w.WriteHeader(grpcCodeToHTTPCode(st.Code()))
_ = json.NewEncoder(w).Encode(http_resp.Error(http_resp.NewCode(code, msg))) _ = json.NewEncoder(w).Encode(httpresp.Error(httpresp.NewCode(code, msg)))
} }
// 这里定义 Internal 属于业务错误,其他的属于 500 报错 // 这里定义 Internal 属于业务错误,其他的属于 500 报错

View File

@@ -2,7 +2,7 @@ package wrapper
import ( import (
"encoding/json" "encoding/json"
"git.hlsq.asia/mmorpg/service-common/net/http/http_resp" "git.hlsq.asia/alex/service-common/net/http/httpresp"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"io" "io"
) )
@@ -20,9 +20,9 @@ func NewWrappedMarshaler(inner runtime.Marshaler) *WrappedMarshaler {
func (w *WrappedMarshaler) Marshal(v interface{}) ([]byte, error) { func (w *WrappedMarshaler) Marshal(v interface{}) ([]byte, error) {
dataBytes, err := w.inner.Marshal(v) dataBytes, err := w.inner.Marshal(v)
if err != nil { if err != nil {
return json.Marshal(http_resp.Error(http_resp.Failed)) return json.Marshal(httpresp.Error(httpresp.Failed))
} }
return json.Marshal(http_resp.Success(json.RawMessage(dataBytes))) return json.Marshal(httpresp.Success(json.RawMessage(dataBytes)))
} }
func (w *WrappedMarshaler) Unmarshal(data []byte, v interface{}) error { func (w *WrappedMarshaler) Unmarshal(data []byte, v interface{}) error {

View File

@@ -1,13 +1,11 @@
package ws_gateway package wsgateway
import ( import (
"fmt" "fmt"
"git.hlsq.asia/mmorpg/service-common/log" "git.hlsq.asia/alex/service-common/log"
"git.hlsq.asia/mmorpg/service-common/net/socket" "git.hlsq.asia/alex/service-common/net/socket"
"git.hlsq.asia/mmorpg/service-common/utils" "git.hlsq.asia/alex/service-gateway/internal/handler/wshandler/client"
"git.hlsq.asia/mmorpg/service-gateway/config" "git.hlsq.asia/alex/service-gateway/internal/handler/wshandler/login"
"git.hlsq.asia/mmorpg/service-gateway/internal/handler/ws_handler/client"
"git.hlsq.asia/mmorpg/service-gateway/internal/handler/ws_handler/login"
"go.uber.org/zap" "go.uber.org/zap"
"time" "time"
) )
@@ -27,16 +25,11 @@ func (g *GatewayWsServer) OnHandShake(conn socket.ISocketConn) socket.Action {
g.logger.Warnf("token is invalid") g.logger.Warnf("token is invalid")
return socket.Close return socket.Close
} }
claims, err := utils.ParseToken(token, config.Get().Auth.Secret)
if err != nil {
g.logger.Warnf("token is invalid")
return socket.Close
}
cli := client.NewClient(claims.USN, conn) cli := client.NewClient(conn)
conn.SetParam("client", cli) conn.SetParam("client", cli)
if !login.GetLoginQueue().AddToLoginQueue(&login.User{Cli: cli, Token: token}) { if !login.GetLoginQueue().AddToLoginQueue(&login.User{Cli: cli, Token: token}) {
g.logger.Warnf("AddToLoginQueue err, login queue full, usn: %v", claims.USN) g.logger.Warnf("AddToLoginQueue err, login queue full")
return socket.Close return socket.Close
} }
return socket.None return socket.None
@@ -44,7 +37,7 @@ func (g *GatewayWsServer) OnHandShake(conn socket.ISocketConn) socket.Action {
func (g *GatewayWsServer) OnMessage(conn socket.ISocketConn, bytes []byte) socket.Action { func (g *GatewayWsServer) OnMessage(conn socket.ISocketConn, bytes []byte) socket.Action {
cli, ok := conn.GetParam("client").(*client.Client) cli, ok := conn.GetParam("client").(*client.Client)
if !ok || cli.USN == "" || cli.Status != 1 { if !ok || cli.USN == 0 || cli.Status != 1 {
return socket.Close return socket.Close
} }
cli.OnEvent(&client.ClientEvent{Msg: bytes}) cli.OnEvent(&client.ClientEvent{Msg: bytes})
@@ -53,7 +46,7 @@ func (g *GatewayWsServer) OnMessage(conn socket.ISocketConn, bytes []byte) socke
func (g *GatewayWsServer) OnPong(conn socket.ISocketConn) { func (g *GatewayWsServer) OnPong(conn socket.ISocketConn) {
cli, ok := conn.GetParam("client").(*client.Client) cli, ok := conn.GetParam("client").(*client.Client)
if !ok || cli.USN == "" { if !ok || cli.USN == 0 {
return return
} }
cli.OnEvent(&client.PongEvent{}) cli.OnEvent(&client.PongEvent{})

View File

@@ -1,9 +1,9 @@
package testutil package testutil
import ( import (
config2 "git.hlsq.asia/mmorpg/service-common/config" config2 "git.hlsq.asia/alex/service-common/config"
"git.hlsq.asia/mmorpg/service-common/db/redis" "git.hlsq.asia/alex/service-common/db/redis"
"git.hlsq.asia/mmorpg/service-gateway/config" "git.hlsq.asia/alex/service-gateway/config"
"github.com/alicebob/miniredis/v2" "github.com/alicebob/miniredis/v2"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
) )
@@ -28,7 +28,6 @@ func (ts *TestSuite) SetupSuite() {
}, },
}, },
Auth: &config.AuthConfig{ Auth: &config.AuthConfig{
Secret: "test",
ShortExpire: 15, ShortExpire: 15,
LongExpire: 10080, LongExpire: 10080,
}, },

View File

@@ -2,12 +2,16 @@ package main
import ( import (
"fmt" "fmt"
"git.hlsq.asia/mmorpg/service-gateway/app" "git.hlsq.asia/alex/service-gateway/app"
"git.hlsq.asia/alex/service-gateway/config"
"github.com/judwhite/go-svc" "github.com/judwhite/go-svc"
"syscall" "syscall"
) )
func main() { func main() {
if err := config.LoadConfig(); err != nil {
fmt.Println(err)
}
if err := svc.Run(&app.Program{}, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL); err != nil { if err := svc.Run(&app.Program{}, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL); err != nil {
fmt.Println(err) fmt.Println(err)
} }