feat 结构调整
This commit is contained in:
@@ -2,9 +2,7 @@ package mysql
|
||||
|
||||
import (
|
||||
"common/config"
|
||||
pointQuery "common/db/mysql/point/query"
|
||||
"common/log"
|
||||
"database/sql"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
@@ -13,23 +11,14 @@ import (
|
||||
|
||||
type DBName string
|
||||
|
||||
const (
|
||||
DBNamePoint DBName = "point"
|
||||
)
|
||||
|
||||
var dbs = make(map[DBName]*sql.DB)
|
||||
var queryS = make(map[DBName]interface{})
|
||||
var dbs = make(map[DBName]*gorm.DB)
|
||||
|
||||
func Init(cfg map[string]*config.MySQLConfig) error {
|
||||
for name, oneConfig := range cfg {
|
||||
switch DBName(name) {
|
||||
case DBNamePoint:
|
||||
if db, err := initOneDB(oneConfig); err != nil {
|
||||
return err
|
||||
} else {
|
||||
dbs[DBNamePoint], _ = db.DB()
|
||||
queryS[DBNamePoint] = pointQuery.Use(db)
|
||||
}
|
||||
if db, err := initOneDB(oneConfig); err != nil {
|
||||
return err
|
||||
} else {
|
||||
dbs[DBName(name)] = db
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -73,15 +62,12 @@ func parseLogLevel(logLevel string) logger.LogLevel {
|
||||
return logger.Info
|
||||
}
|
||||
|
||||
func GetPointDB() *pointQuery.Query {
|
||||
return getQuery[*pointQuery.Query](DBNamePoint)
|
||||
}
|
||||
|
||||
func getQuery[T any](dbName DBName) (result T) {
|
||||
if q, ok := queryS[dbName]; ok {
|
||||
result, _ = q.(T)
|
||||
func GetDB(dbName DBName) *gorm.DB {
|
||||
if q, ok := dbs[dbName]; ok {
|
||||
return q
|
||||
}
|
||||
return
|
||||
log.Errorf("db %s not found", dbName)
|
||||
return nil
|
||||
}
|
||||
|
||||
func Close() error {
|
||||
@@ -89,8 +75,10 @@ func Close() error {
|
||||
return nil
|
||||
}
|
||||
for name, db := range dbs {
|
||||
if err := db.Close(); err != nil {
|
||||
log.Errorf("close db %s error: %v", name, err)
|
||||
if sqlDB, _ := db.DB(); sqlDB != nil {
|
||||
if err := sqlDB.Close(); err != nil {
|
||||
log.Errorf("close db %s error: %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const TableNameUser = "users"
|
||||
|
||||
// User mapped from table <users>
|
||||
type User struct {
|
||||
ID int64 `gorm:"column:id;primaryKey;autoIncrement:true" json:"id"`
|
||||
Sn string `gorm:"column:sn;not null;comment:业务唯一编号" json:"sn"` // 业务唯一编号
|
||||
Name string `gorm:"column:name;not null" json:"name"`
|
||||
CreatedAt time.Time `gorm:"column:created_at;not null" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at;not null" json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"column:deleted_at" json:"deleted_at"`
|
||||
}
|
||||
|
||||
// TableName User's table name
|
||||
func (*User) TableName() string {
|
||||
return TableNameUser
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
|
||||
package query
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"gorm.io/gen"
|
||||
|
||||
"gorm.io/plugin/dbresolver"
|
||||
)
|
||||
|
||||
func Use(db *gorm.DB, opts ...gen.DOOption) *Query {
|
||||
return &Query{
|
||||
db: db,
|
||||
User: newUser(db, opts...),
|
||||
}
|
||||
}
|
||||
|
||||
type Query struct {
|
||||
db *gorm.DB
|
||||
|
||||
User user
|
||||
}
|
||||
|
||||
func (q *Query) Available() bool { return q.db != nil }
|
||||
|
||||
func (q *Query) clone(db *gorm.DB) *Query {
|
||||
return &Query{
|
||||
db: db,
|
||||
User: q.User.clone(db),
|
||||
}
|
||||
}
|
||||
|
||||
func (q *Query) ReadDB() *Query {
|
||||
return q.ReplaceDB(q.db.Clauses(dbresolver.Read))
|
||||
}
|
||||
|
||||
func (q *Query) WriteDB() *Query {
|
||||
return q.ReplaceDB(q.db.Clauses(dbresolver.Write))
|
||||
}
|
||||
|
||||
func (q *Query) ReplaceDB(db *gorm.DB) *Query {
|
||||
return &Query{
|
||||
db: db,
|
||||
User: q.User.replaceDB(db),
|
||||
}
|
||||
}
|
||||
|
||||
type queryCtx struct {
|
||||
User *userDo
|
||||
}
|
||||
|
||||
func (q *Query) WithContext(ctx context.Context) *queryCtx {
|
||||
return &queryCtx{
|
||||
User: q.User.WithContext(ctx),
|
||||
}
|
||||
}
|
||||
|
||||
func (q *Query) Transaction(fc func(tx *Query) error, opts ...*sql.TxOptions) error {
|
||||
return q.db.Transaction(func(tx *gorm.DB) error { return fc(q.clone(tx)) }, opts...)
|
||||
}
|
||||
|
||||
func (q *Query) Begin(opts ...*sql.TxOptions) *QueryTx {
|
||||
tx := q.db.Begin(opts...)
|
||||
return &QueryTx{Query: q.clone(tx), Error: tx.Error}
|
||||
}
|
||||
|
||||
type QueryTx struct {
|
||||
*Query
|
||||
Error error
|
||||
}
|
||||
|
||||
func (q *QueryTx) Commit() error {
|
||||
return q.db.Commit().Error
|
||||
}
|
||||
|
||||
func (q *QueryTx) Rollback() error {
|
||||
return q.db.Rollback().Error
|
||||
}
|
||||
|
||||
func (q *QueryTx) SavePoint(name string) error {
|
||||
return q.db.SavePoint(name).Error
|
||||
}
|
||||
|
||||
func (q *QueryTx) RollbackTo(name string) error {
|
||||
return q.db.RollbackTo(name).Error
|
||||
}
|
||||
@@ -1,346 +0,0 @@
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
|
||||
package query
|
||||
|
||||
import (
|
||||
"common/db/mysql/point/model"
|
||||
"context"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
"gorm.io/gorm/schema"
|
||||
|
||||
"gorm.io/gen"
|
||||
"gorm.io/gen/field"
|
||||
|
||||
"gorm.io/plugin/dbresolver"
|
||||
)
|
||||
|
||||
func newUser(db *gorm.DB, opts ...gen.DOOption) user {
|
||||
_user := user{}
|
||||
|
||||
_user.userDo.UseDB(db, opts...)
|
||||
_user.userDo.UseModel(&model.User{})
|
||||
|
||||
tableName := _user.userDo.TableName()
|
||||
_user.ALL = field.NewAsterisk(tableName)
|
||||
_user.ID = field.NewInt64(tableName, "id")
|
||||
_user.Sn = field.NewString(tableName, "sn")
|
||||
_user.Name = field.NewString(tableName, "name")
|
||||
_user.CreatedAt = field.NewTime(tableName, "created_at")
|
||||
_user.UpdatedAt = field.NewTime(tableName, "updated_at")
|
||||
_user.DeletedAt = field.NewField(tableName, "deleted_at")
|
||||
|
||||
_user.fillFieldMap()
|
||||
|
||||
return _user
|
||||
}
|
||||
|
||||
type user struct {
|
||||
userDo userDo
|
||||
|
||||
ALL field.Asterisk
|
||||
ID field.Int64
|
||||
Sn field.String // 业务唯一编号
|
||||
Name field.String
|
||||
CreatedAt field.Time
|
||||
UpdatedAt field.Time
|
||||
DeletedAt field.Field
|
||||
|
||||
fieldMap map[string]field.Expr
|
||||
}
|
||||
|
||||
func (u user) Table(newTableName string) *user {
|
||||
u.userDo.UseTable(newTableName)
|
||||
return u.updateTableName(newTableName)
|
||||
}
|
||||
|
||||
func (u user) As(alias string) *user {
|
||||
u.userDo.DO = *(u.userDo.As(alias).(*gen.DO))
|
||||
return u.updateTableName(alias)
|
||||
}
|
||||
|
||||
func (u *user) updateTableName(table string) *user {
|
||||
u.ALL = field.NewAsterisk(table)
|
||||
u.ID = field.NewInt64(table, "id")
|
||||
u.Sn = field.NewString(table, "sn")
|
||||
u.Name = field.NewString(table, "name")
|
||||
u.CreatedAt = field.NewTime(table, "created_at")
|
||||
u.UpdatedAt = field.NewTime(table, "updated_at")
|
||||
u.DeletedAt = field.NewField(table, "deleted_at")
|
||||
|
||||
u.fillFieldMap()
|
||||
|
||||
return u
|
||||
}
|
||||
|
||||
func (u *user) WithContext(ctx context.Context) *userDo { return u.userDo.WithContext(ctx) }
|
||||
|
||||
func (u user) TableName() string { return u.userDo.TableName() }
|
||||
|
||||
func (u user) Alias() string { return u.userDo.Alias() }
|
||||
|
||||
func (u user) Columns(cols ...field.Expr) gen.Columns { return u.userDo.Columns(cols...) }
|
||||
|
||||
func (u *user) GetFieldByName(fieldName string) (field.OrderExpr, bool) {
|
||||
_f, ok := u.fieldMap[fieldName]
|
||||
if !ok || _f == nil {
|
||||
return nil, false
|
||||
}
|
||||
_oe, ok := _f.(field.OrderExpr)
|
||||
return _oe, ok
|
||||
}
|
||||
|
||||
func (u *user) fillFieldMap() {
|
||||
u.fieldMap = make(map[string]field.Expr, 6)
|
||||
u.fieldMap["id"] = u.ID
|
||||
u.fieldMap["sn"] = u.Sn
|
||||
u.fieldMap["name"] = u.Name
|
||||
u.fieldMap["created_at"] = u.CreatedAt
|
||||
u.fieldMap["updated_at"] = u.UpdatedAt
|
||||
u.fieldMap["deleted_at"] = u.DeletedAt
|
||||
}
|
||||
|
||||
func (u user) clone(db *gorm.DB) user {
|
||||
u.userDo.ReplaceConnPool(db.Statement.ConnPool)
|
||||
return u
|
||||
}
|
||||
|
||||
func (u user) replaceDB(db *gorm.DB) user {
|
||||
u.userDo.ReplaceDB(db)
|
||||
return u
|
||||
}
|
||||
|
||||
type userDo struct{ gen.DO }
|
||||
|
||||
func (u userDo) Debug() *userDo {
|
||||
return u.withDO(u.DO.Debug())
|
||||
}
|
||||
|
||||
func (u userDo) WithContext(ctx context.Context) *userDo {
|
||||
return u.withDO(u.DO.WithContext(ctx))
|
||||
}
|
||||
|
||||
func (u userDo) ReadDB() *userDo {
|
||||
return u.Clauses(dbresolver.Read)
|
||||
}
|
||||
|
||||
func (u userDo) WriteDB() *userDo {
|
||||
return u.Clauses(dbresolver.Write)
|
||||
}
|
||||
|
||||
func (u userDo) Session(config *gorm.Session) *userDo {
|
||||
return u.withDO(u.DO.Session(config))
|
||||
}
|
||||
|
||||
func (u userDo) Clauses(conds ...clause.Expression) *userDo {
|
||||
return u.withDO(u.DO.Clauses(conds...))
|
||||
}
|
||||
|
||||
func (u userDo) Returning(value interface{}, columns ...string) *userDo {
|
||||
return u.withDO(u.DO.Returning(value, columns...))
|
||||
}
|
||||
|
||||
func (u userDo) Not(conds ...gen.Condition) *userDo {
|
||||
return u.withDO(u.DO.Not(conds...))
|
||||
}
|
||||
|
||||
func (u userDo) Or(conds ...gen.Condition) *userDo {
|
||||
return u.withDO(u.DO.Or(conds...))
|
||||
}
|
||||
|
||||
func (u userDo) Select(conds ...field.Expr) *userDo {
|
||||
return u.withDO(u.DO.Select(conds...))
|
||||
}
|
||||
|
||||
func (u userDo) Where(conds ...gen.Condition) *userDo {
|
||||
return u.withDO(u.DO.Where(conds...))
|
||||
}
|
||||
|
||||
func (u userDo) Order(conds ...field.Expr) *userDo {
|
||||
return u.withDO(u.DO.Order(conds...))
|
||||
}
|
||||
|
||||
func (u userDo) Distinct(cols ...field.Expr) *userDo {
|
||||
return u.withDO(u.DO.Distinct(cols...))
|
||||
}
|
||||
|
||||
func (u userDo) Omit(cols ...field.Expr) *userDo {
|
||||
return u.withDO(u.DO.Omit(cols...))
|
||||
}
|
||||
|
||||
func (u userDo) Join(table schema.Tabler, on ...field.Expr) *userDo {
|
||||
return u.withDO(u.DO.Join(table, on...))
|
||||
}
|
||||
|
||||
func (u userDo) LeftJoin(table schema.Tabler, on ...field.Expr) *userDo {
|
||||
return u.withDO(u.DO.LeftJoin(table, on...))
|
||||
}
|
||||
|
||||
func (u userDo) RightJoin(table schema.Tabler, on ...field.Expr) *userDo {
|
||||
return u.withDO(u.DO.RightJoin(table, on...))
|
||||
}
|
||||
|
||||
func (u userDo) Group(cols ...field.Expr) *userDo {
|
||||
return u.withDO(u.DO.Group(cols...))
|
||||
}
|
||||
|
||||
func (u userDo) Having(conds ...gen.Condition) *userDo {
|
||||
return u.withDO(u.DO.Having(conds...))
|
||||
}
|
||||
|
||||
func (u userDo) Limit(limit int) *userDo {
|
||||
return u.withDO(u.DO.Limit(limit))
|
||||
}
|
||||
|
||||
func (u userDo) Offset(offset int) *userDo {
|
||||
return u.withDO(u.DO.Offset(offset))
|
||||
}
|
||||
|
||||
func (u userDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *userDo {
|
||||
return u.withDO(u.DO.Scopes(funcs...))
|
||||
}
|
||||
|
||||
func (u userDo) Unscoped() *userDo {
|
||||
return u.withDO(u.DO.Unscoped())
|
||||
}
|
||||
|
||||
func (u userDo) Create(values ...*model.User) error {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
return u.DO.Create(values)
|
||||
}
|
||||
|
||||
func (u userDo) CreateInBatches(values []*model.User, batchSize int) error {
|
||||
return u.DO.CreateInBatches(values, batchSize)
|
||||
}
|
||||
|
||||
// Save : !!! underlying implementation is different with GORM
|
||||
// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values)
|
||||
func (u userDo) Save(values ...*model.User) error {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
return u.DO.Save(values)
|
||||
}
|
||||
|
||||
func (u userDo) First() (*model.User, error) {
|
||||
if result, err := u.DO.First(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.User), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (u userDo) Take() (*model.User, error) {
|
||||
if result, err := u.DO.Take(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.User), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (u userDo) Last() (*model.User, error) {
|
||||
if result, err := u.DO.Last(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.User), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (u userDo) Find() ([]*model.User, error) {
|
||||
result, err := u.DO.Find()
|
||||
return result.([]*model.User), err
|
||||
}
|
||||
|
||||
func (u userDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.User, err error) {
|
||||
buf := make([]*model.User, 0, batchSize)
|
||||
err = u.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error {
|
||||
defer func() { results = append(results, buf...) }()
|
||||
return fc(tx, batch)
|
||||
})
|
||||
return results, err
|
||||
}
|
||||
|
||||
func (u userDo) FindInBatches(result *[]*model.User, batchSize int, fc func(tx gen.Dao, batch int) error) error {
|
||||
return u.DO.FindInBatches(result, batchSize, fc)
|
||||
}
|
||||
|
||||
func (u userDo) Attrs(attrs ...field.AssignExpr) *userDo {
|
||||
return u.withDO(u.DO.Attrs(attrs...))
|
||||
}
|
||||
|
||||
func (u userDo) Assign(attrs ...field.AssignExpr) *userDo {
|
||||
return u.withDO(u.DO.Assign(attrs...))
|
||||
}
|
||||
|
||||
func (u userDo) Joins(fields ...field.RelationField) *userDo {
|
||||
for _, _f := range fields {
|
||||
u = *u.withDO(u.DO.Joins(_f))
|
||||
}
|
||||
return &u
|
||||
}
|
||||
|
||||
func (u userDo) Preload(fields ...field.RelationField) *userDo {
|
||||
for _, _f := range fields {
|
||||
u = *u.withDO(u.DO.Preload(_f))
|
||||
}
|
||||
return &u
|
||||
}
|
||||
|
||||
func (u userDo) FirstOrInit() (*model.User, error) {
|
||||
if result, err := u.DO.FirstOrInit(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.User), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (u userDo) FirstOrCreate() (*model.User, error) {
|
||||
if result, err := u.DO.FirstOrCreate(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.User), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (u userDo) FindByPage(offset int, limit int) (result []*model.User, count int64, err error) {
|
||||
result, err = u.Offset(offset).Limit(limit).Find()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if size := len(result); 0 < limit && 0 < size && size < limit {
|
||||
count = int64(size + offset)
|
||||
return
|
||||
}
|
||||
|
||||
count, err = u.Offset(-1).Limit(-1).Count()
|
||||
return
|
||||
}
|
||||
|
||||
func (u userDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) {
|
||||
count, err = u.Count()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
err = u.Offset(offset).Limit(limit).Scan(result)
|
||||
return
|
||||
}
|
||||
|
||||
func (u userDo) Scan(result interface{}) (err error) {
|
||||
return u.DO.Scan(result)
|
||||
}
|
||||
|
||||
func (u userDo) Delete(models ...*model.User) (result gen.ResultInfo, err error) {
|
||||
return u.DO.Delete(models)
|
||||
}
|
||||
|
||||
func (u *userDo) withDO(do gen.Dao) *userDo {
|
||||
u.DO = *do.(*gen.DO)
|
||||
return u
|
||||
}
|
||||
@@ -16,9 +16,15 @@ var (
|
||||
)
|
||||
|
||||
var (
|
||||
KeyDiscoverGateway = KeyDiscoverService + "/gateway" // 网关服
|
||||
KeyDiscoverDatabase = KeyDiscoverService + "/database" // 数据服
|
||||
KeyDiscoverScene = KeyDiscoverService + "/scene" // 场景服
|
||||
KeyDiscoverServiceNameGateway = "gateway" // 网关服
|
||||
KeyDiscoverServiceNameScene = "scene" // 场景服
|
||||
KeyDiscoverServiceNameUser = "user" // 用户中心
|
||||
)
|
||||
|
||||
var (
|
||||
KeyDiscoverGateway = KeyDiscoverService + "/" + KeyDiscoverServiceNameGateway // 网关服
|
||||
KeyDiscoverScene = KeyDiscoverService + "/" + KeyDiscoverServiceNameScene // 场景服
|
||||
KeyDiscoverUser = KeyDiscoverService + "/" + KeyDiscoverServiceNameUser // 用户中心
|
||||
)
|
||||
|
||||
// ServiceProvider 服务提供者
|
||||
|
||||
@@ -5,6 +5,7 @@ go 1.23.1
|
||||
require (
|
||||
github.com/bwmarrin/snowflake v0.3.0
|
||||
github.com/gobwas/ws v1.4.0
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3
|
||||
github.com/natefinch/lumberjack v2.0.0+incompatible
|
||||
github.com/panjf2000/gnet/v2 v2.9.1
|
||||
github.com/redis/go-redis/v9 v9.10.0
|
||||
@@ -12,6 +13,7 @@ require (
|
||||
go.etcd.io/etcd/api/v3 v3.6.1
|
||||
go.etcd.io/etcd/client/v3 v3.6.1
|
||||
go.uber.org/zap v1.27.0
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250303144028-a0af3efb3deb
|
||||
google.golang.org/grpc v1.71.1
|
||||
google.golang.org/protobuf v1.36.5
|
||||
gorm.io/driver/mysql v1.6.0
|
||||
@@ -35,7 +37,6 @@ require (
|
||||
github.com/gogo/protobuf v1.3.2 // indirect
|
||||
github.com/golang/protobuf v1.5.4 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/panjf2000/ants/v2 v2.11.3 // indirect
|
||||
@@ -56,7 +57,6 @@ require (
|
||||
golang.org/x/sys v0.34.0 // indirect
|
||||
golang.org/x/text v0.28.0 // indirect
|
||||
golang.org/x/tools v0.35.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250303144028-a0af3efb3deb // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250303144028-a0af3efb3deb // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
|
||||
@@ -3,6 +3,7 @@ package grpc_conn
|
||||
import (
|
||||
"common/log"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/keepalive"
|
||||
"time"
|
||||
)
|
||||
@@ -18,7 +19,7 @@ func NewGrpcConnection(sid int64, address string) (*GrpcConnection, error) {
|
||||
}
|
||||
conn, err := grpc.NewClient(
|
||||
address,
|
||||
grpc.WithInsecure(),
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
grpc.WithKeepaliveParams(
|
||||
keepalive.ClientParameters{
|
||||
Time: 30 * time.Second, // 保活探测包发送的时间间隔
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
package grpc_conn
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"google.golang.org/grpc/stats"
|
||||
)
|
||||
|
||||
// 1. 实现 stats.Handler 接口
|
||||
type StatsHandler struct{}
|
||||
|
||||
func (h *StatsHandler) TagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context {
|
||||
// 给 RPC 调用打标签(例如记录方法名)
|
||||
return context.WithValue(ctx, "rpc_method", info.FullMethodName)
|
||||
}
|
||||
|
||||
func (h *StatsHandler) HandleRPC(ctx context.Context, s stats.RPCStats) {
|
||||
// 处理 RPC 统计信息
|
||||
switch t := s.(type) {
|
||||
case *stats.Begin:
|
||||
fmt.Printf("RPC started: %s\n", ctx.Value("rpc_method"))
|
||||
case *stats.End:
|
||||
fmt.Printf("RPC finished: %s (duration: %v)\n",
|
||||
ctx.Value("rpc_method"), t.EndTime.Sub(t.BeginTime))
|
||||
case *stats.InPayload:
|
||||
fmt.Printf("Received %d bytes\n", t.WireLength)
|
||||
case *stats.OutPayload:
|
||||
fmt.Printf("Sent %d bytes\n", t.WireLength)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *StatsHandler) TagConn(ctx context.Context, info *stats.ConnTagInfo) context.Context {
|
||||
// 给连接打标签
|
||||
return ctx
|
||||
}
|
||||
|
||||
func (h *StatsHandler) HandleConn(ctx context.Context, s stats.ConnStats) {
|
||||
// 处理连接事件
|
||||
switch s.(type) {
|
||||
case *stats.ConnBegin:
|
||||
fmt.Println("Connection established")
|
||||
case *stats.ConnEnd:
|
||||
fmt.Println("Connection closed")
|
||||
}
|
||||
}
|
||||
30
Server/common/net/grpc/resolver/conn.go
Normal file
30
Server/common/net/grpc/resolver/conn.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package resolver
|
||||
|
||||
import (
|
||||
"common/log"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/keepalive"
|
||||
"time"
|
||||
)
|
||||
|
||||
func NewGrpcConnection(target string) (*grpc.ClientConn, error) {
|
||||
cc, err := grpc.NewClient(
|
||||
target,
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
grpc.WithDefaultServiceConfig(`{"loadBalancingConfig": [{"round_robin": {}}]}`),
|
||||
grpc.WithKeepaliveParams(
|
||||
keepalive.ClientParameters{
|
||||
Time: 30 * time.Second, // 保活探测包发送的时间间隔
|
||||
Timeout: 10 * time.Second, // 保活探测包的超时时间
|
||||
PermitWithoutStream: true,
|
||||
},
|
||||
),
|
||||
//grpc.WithStatsHandler(&StatsHandler{}),
|
||||
)
|
||||
if err != nil {
|
||||
log.Errorf("create grpc err: %v, target: %v", err, target)
|
||||
return nil, err
|
||||
}
|
||||
return cc, nil
|
||||
}
|
||||
84
Server/common/net/grpc/resolver/etcd_resolver.go
Normal file
84
Server/common/net/grpc/resolver/etcd_resolver.go
Normal file
@@ -0,0 +1,84 @@
|
||||
package resolver
|
||||
|
||||
import (
|
||||
"common/db/etcd"
|
||||
"common/discover/common"
|
||||
"common/log"
|
||||
"context"
|
||||
"go.etcd.io/etcd/client/v3"
|
||||
"google.golang.org/grpc/resolver"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const etcdSchema = "etcd"
|
||||
|
||||
func init() {
|
||||
resolver.Register(&etcdBuilder{})
|
||||
}
|
||||
|
||||
type etcdBuilder struct{}
|
||||
|
||||
func (*etcdBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) {
|
||||
serviceName := strings.TrimPrefix(target.URL.Path, "/")
|
||||
r := &etcdResolver{
|
||||
serviceName: serviceName,
|
||||
cc: cc,
|
||||
}
|
||||
r.start()
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (*etcdBuilder) Scheme() string { return etcdSchema }
|
||||
|
||||
type etcdResolver struct {
|
||||
serviceName string
|
||||
cc resolver.ClientConn
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (r *etcdResolver) start() {
|
||||
r.ctx, r.cancel = context.WithCancel(context.Background())
|
||||
r.update()
|
||||
go r.watch()
|
||||
}
|
||||
|
||||
func (r *etcdResolver) getPrefix() string {
|
||||
return common.KeyDiscoverService + "/" + r.serviceName
|
||||
}
|
||||
|
||||
func (r *etcdResolver) update() {
|
||||
resp, err := etcd.GetClient().Get(r.getPrefix(), clientv3.WithPrefix())
|
||||
if err != nil {
|
||||
log.Errorf("etcd resolver get error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
var addrArray []resolver.Address
|
||||
for _, kv := range resp.Kvs {
|
||||
addr := string(kv.Value)
|
||||
if addr != "" {
|
||||
addrArray = append(addrArray, resolver.Address{Addr: addr})
|
||||
}
|
||||
}
|
||||
|
||||
_ = r.cc.UpdateState(resolver.State{Addresses: addrArray})
|
||||
}
|
||||
|
||||
func (r *etcdResolver) watch() {
|
||||
watchCh := etcd.GetClient().Watch(r.getPrefix(), clientv3.WithPrefix())
|
||||
for w := range watchCh {
|
||||
if w.Err() != nil {
|
||||
continue
|
||||
}
|
||||
r.update()
|
||||
}
|
||||
}
|
||||
|
||||
func (r *etcdResolver) ResolveNow(resolver.ResolveNowOptions) {
|
||||
r.update()
|
||||
}
|
||||
|
||||
func (r *etcdResolver) Close() {
|
||||
r.cancel()
|
||||
}
|
||||
35
Server/common/net/grpc/resolver/resolver_mgr.go
Normal file
35
Server/common/net/grpc/resolver/resolver_mgr.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package resolver
|
||||
|
||||
import (
|
||||
"google.golang.org/grpc"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var (
|
||||
mu = sync.RWMutex{}
|
||||
conn = make(map[string]*grpc.ClientConn)
|
||||
)
|
||||
|
||||
func GetGrpcClientConn(target string) (*grpc.ClientConn, error) {
|
||||
mu.RLock()
|
||||
if c, ok := conn[target]; ok && c != nil {
|
||||
mu.RUnlock()
|
||||
return c, nil
|
||||
}
|
||||
mu.RUnlock()
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
if c, ok := conn[target]; ok && c != nil {
|
||||
return c, nil
|
||||
}
|
||||
|
||||
newConn, err := NewGrpcConnection(target)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
conn[target] = newConn
|
||||
return newConn, nil
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package service
|
||||
import (
|
||||
"common/discover"
|
||||
"common/discover/common"
|
||||
"common/net/grpc/resolver"
|
||||
"common/proto/ss/grpc_pb"
|
||||
)
|
||||
|
||||
@@ -14,6 +15,14 @@ func SceneNewClient(sid ...int64) (grpc_pb.SceneClient, error) {
|
||||
return grpc_pb.NewSceneClient(c), nil
|
||||
}
|
||||
|
||||
func SceneNewClientLB() (grpc_pb.SceneClient, error) {
|
||||
c, err := resolver.GetGrpcClientConn("etcd:///" + common.KeyDiscoverServiceNameScene)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return grpc_pb.NewSceneClient(c), nil
|
||||
}
|
||||
|
||||
func SceneNewBroadcastClient() map[int64]grpc_pb.SceneClient {
|
||||
clientM := make(map[int64]grpc_pb.SceneClient)
|
||||
connM := discover.FindServerAll(common.KeyDiscoverScene)
|
||||
|
||||
24
Server/common/net/grpc/service/client_user.go
Normal file
24
Server/common/net/grpc/service/client_user.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"common/discover"
|
||||
"common/discover/common"
|
||||
"common/net/grpc/resolver"
|
||||
"common/proto/ss/grpc_pb"
|
||||
)
|
||||
|
||||
func UserNewClient(sid ...int64) (grpc_pb.UserClient, error) {
|
||||
c, err := discover.FindServer(common.KeyDiscoverUser, sid...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return grpc_pb.NewUserClient(c), nil
|
||||
}
|
||||
|
||||
func UserNewClientLB() (grpc_pb.UserClient, error) {
|
||||
c, err := resolver.GetGrpcClientConn("etcd:///" + common.KeyDiscoverServiceNameUser)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return grpc_pb.NewUserClient(c), nil
|
||||
}
|
||||
@@ -7,7 +7,9 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/keepalive"
|
||||
"google.golang.org/grpc/status"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -51,6 +53,7 @@ func (s *Base) Init(addr string, port int32) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
log.Errorf("server Panic: %v", r)
|
||||
err = status.Error(codes.Internal, fmt.Sprintf("%v", r))
|
||||
}
|
||||
}()
|
||||
resp, err = handler(ctx, req)
|
||||
|
||||
46
Server/common/net/http/http_resp/code.go
Normal file
46
Server/common/net/http/http_resp/code.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package http_resp
|
||||
|
||||
import (
|
||||
"common/proto/ss/ss_common"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
var (
|
||||
OK = NewCode(0, "OK")
|
||||
Failed = NewCode(1, "Failed")
|
||||
ParamError = NewCode(1001, "参数错误")
|
||||
NameEmpty = NewCode(1002, "名称不能为空")
|
||||
NameDuplicate = NewCode(1003, "名称或编号不能重复")
|
||||
ListEmpty = NewCode(1004, "列表不能为空")
|
||||
RepeatCommit = NewCode(1005, "请勿重复提交")
|
||||
)
|
||||
|
||||
type Code struct {
|
||||
code int
|
||||
error string
|
||||
}
|
||||
|
||||
func NewCode(code int, error string) *Code {
|
||||
return &Code{
|
||||
code: code,
|
||||
error: error,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Code) Code() int {
|
||||
return c.code
|
||||
}
|
||||
|
||||
func (c *Code) Error() string {
|
||||
return c.error
|
||||
}
|
||||
|
||||
func (c *Code) Wrap() error {
|
||||
st := status.New(codes.Unknown, c.Error())
|
||||
st, _ = st.WithDetails(&ss_common.ErrorInfo{
|
||||
Code: int32(c.Code()),
|
||||
Msg: c.Error(),
|
||||
})
|
||||
return st.Err()
|
||||
}
|
||||
22
Server/common/net/http/http_resp/response.go
Normal file
22
Server/common/net/http/http_resp/response.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package http_resp
|
||||
|
||||
type RespJsonData struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Data interface{} `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
func Success(data interface{}) *RespJsonData {
|
||||
return &RespJsonData{
|
||||
Code: OK.Code(),
|
||||
Msg: OK.Error(),
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
|
||||
func Error(code int, message string) *RespJsonData {
|
||||
return &RespJsonData{
|
||||
Code: code,
|
||||
Msg: message,
|
||||
}
|
||||
}
|
||||
224
Server/common/proto/ss/grpc_pb/service_user.pb.go
Normal file
224
Server/common/proto/ss/grpc_pb/service_user.pb.go
Normal file
@@ -0,0 +1,224 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.32.0
|
||||
// protoc v4.25.1
|
||||
// source: service_user.proto
|
||||
|
||||
package grpc_pb
|
||||
|
||||
import (
|
||||
_ "common/proto/ss/ss_common"
|
||||
_ "google.golang.org/genproto/googleapis/api/annotations"
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
type LoginReq struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
Phone string `protobuf:"bytes,1,opt,name=Phone,json=phone,proto3" json:"Phone,omitempty"` // 手机号
|
||||
Code string `protobuf:"bytes,2,opt,name=Code,json=code,proto3" json:"Code,omitempty"` // 验证码
|
||||
}
|
||||
|
||||
func (x *LoginReq) Reset() {
|
||||
*x = LoginReq{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_service_user_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *LoginReq) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*LoginReq) ProtoMessage() {}
|
||||
|
||||
func (x *LoginReq) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_service_user_proto_msgTypes[0]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use LoginReq.ProtoReflect.Descriptor instead.
|
||||
func (*LoginReq) Descriptor() ([]byte, []int) {
|
||||
return file_service_user_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *LoginReq) GetPhone() string {
|
||||
if x != nil {
|
||||
return x.Phone
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *LoginReq) GetCode() string {
|
||||
if x != nil {
|
||||
return x.Code
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type LoginResp struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
UID int32 `protobuf:"varint,1,opt,name=UID,json=uid,proto3" json:"UID,omitempty"` // 用户ID
|
||||
}
|
||||
|
||||
func (x *LoginResp) Reset() {
|
||||
*x = LoginResp{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_service_user_proto_msgTypes[1]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *LoginResp) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*LoginResp) ProtoMessage() {}
|
||||
|
||||
func (x *LoginResp) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_service_user_proto_msgTypes[1]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use LoginResp.ProtoReflect.Descriptor instead.
|
||||
func (*LoginResp) Descriptor() ([]byte, []int) {
|
||||
return file_service_user_proto_rawDescGZIP(), []int{1}
|
||||
}
|
||||
|
||||
func (x *LoginResp) GetUID() int32 {
|
||||
if x != nil {
|
||||
return x.UID
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
var File_service_user_proto protoreflect.FileDescriptor
|
||||
|
||||
var file_service_user_proto_rawDesc = []byte{
|
||||
0x0a, 0x12, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x5f, 0x75, 0x73, 0x65, 0x72, 0x2e, 0x70,
|
||||
0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x0f, 0x73, 0x73, 0x5f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e,
|
||||
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70,
|
||||
0x69, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72,
|
||||
0x6f, 0x74, 0x6f, 0x22, 0x34, 0x0a, 0x08, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x52, 0x65, 0x71, 0x12,
|
||||
0x14, 0x0a, 0x05, 0x50, 0x68, 0x6f, 0x6e, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05,
|
||||
0x70, 0x68, 0x6f, 0x6e, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x43, 0x6f, 0x64, 0x65, 0x18, 0x02, 0x20,
|
||||
0x01, 0x28, 0x09, 0x52, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x22, 0x1d, 0x0a, 0x09, 0x4c, 0x6f, 0x67,
|
||||
0x69, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x12, 0x10, 0x0a, 0x03, 0x55, 0x49, 0x44, 0x18, 0x01, 0x20,
|
||||
0x01, 0x28, 0x05, 0x52, 0x03, 0x75, 0x69, 0x64, 0x32, 0x3e, 0x0a, 0x04, 0x55, 0x73, 0x65, 0x72,
|
||||
0x12, 0x36, 0x0a, 0x05, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x12, 0x09, 0x2e, 0x4c, 0x6f, 0x67, 0x69,
|
||||
0x6e, 0x52, 0x65, 0x71, 0x1a, 0x0a, 0x2e, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x52, 0x65, 0x73, 0x70,
|
||||
0x22, 0x16, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x10, 0x3a, 0x01, 0x2a, 0x22, 0x0b, 0x2f, 0x75, 0x73,
|
||||
0x65, 0x72, 0x2f, 0x6c, 0x6f, 0x67, 0x69, 0x6e, 0x42, 0x19, 0x5a, 0x17, 0x63, 0x6f, 0x6d, 0x6d,
|
||||
0x6f, 0x6e, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x73, 0x73, 0x2f, 0x67, 0x72, 0x70, 0x63,
|
||||
0x5f, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
|
||||
}
|
||||
|
||||
var (
|
||||
file_service_user_proto_rawDescOnce sync.Once
|
||||
file_service_user_proto_rawDescData = file_service_user_proto_rawDesc
|
||||
)
|
||||
|
||||
func file_service_user_proto_rawDescGZIP() []byte {
|
||||
file_service_user_proto_rawDescOnce.Do(func() {
|
||||
file_service_user_proto_rawDescData = protoimpl.X.CompressGZIP(file_service_user_proto_rawDescData)
|
||||
})
|
||||
return file_service_user_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_service_user_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
|
||||
var file_service_user_proto_goTypes = []interface{}{
|
||||
(*LoginReq)(nil), // 0: LoginReq
|
||||
(*LoginResp)(nil), // 1: LoginResp
|
||||
}
|
||||
var file_service_user_proto_depIdxs = []int32{
|
||||
0, // 0: User.Login:input_type -> LoginReq
|
||||
1, // 1: User.Login:output_type -> LoginResp
|
||||
1, // [1:2] is the sub-list for method output_type
|
||||
0, // [0:1] is the sub-list for method input_type
|
||||
0, // [0:0] is the sub-list for extension type_name
|
||||
0, // [0:0] is the sub-list for extension extendee
|
||||
0, // [0:0] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_service_user_proto_init() }
|
||||
func file_service_user_proto_init() {
|
||||
if File_service_user_proto != nil {
|
||||
return
|
||||
}
|
||||
if !protoimpl.UnsafeEnabled {
|
||||
file_service_user_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*LoginReq); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_service_user_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*LoginResp); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: file_service_user_proto_rawDesc,
|
||||
NumEnums: 0,
|
||||
NumMessages: 2,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
GoTypes: file_service_user_proto_goTypes,
|
||||
DependencyIndexes: file_service_user_proto_depIdxs,
|
||||
MessageInfos: file_service_user_proto_msgTypes,
|
||||
}.Build()
|
||||
File_service_user_proto = out.File
|
||||
file_service_user_proto_rawDesc = nil
|
||||
file_service_user_proto_goTypes = nil
|
||||
file_service_user_proto_depIdxs = nil
|
||||
}
|
||||
154
Server/common/proto/ss/grpc_pb/service_user.pb.gw.go
Normal file
154
Server/common/proto/ss/grpc_pb/service_user.pb.gw.go
Normal file
@@ -0,0 +1,154 @@
|
||||
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
|
||||
// source: service_user.proto
|
||||
|
||||
/*
|
||||
Package grpc_pb is a reverse proxy.
|
||||
|
||||
It translates gRPC into RESTful JSON APIs.
|
||||
*/
|
||||
package grpc_pb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
|
||||
"github.com/grpc-ecosystem/grpc-gateway/v2/utilities"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/grpclog"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// Suppress "imported and not used" errors
|
||||
var (
|
||||
_ codes.Code
|
||||
_ io.Reader
|
||||
_ status.Status
|
||||
_ = errors.New
|
||||
_ = runtime.String
|
||||
_ = utilities.NewDoubleArray
|
||||
_ = metadata.Join
|
||||
)
|
||||
|
||||
func request_User_Login_0(ctx context.Context, marshaler runtime.Marshaler, client UserClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
|
||||
var (
|
||||
protoReq LoginReq
|
||||
metadata runtime.ServerMetadata
|
||||
)
|
||||
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) {
|
||||
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
|
||||
}
|
||||
msg, err := client.Login(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
|
||||
return msg, metadata, err
|
||||
}
|
||||
|
||||
func local_request_User_Login_0(ctx context.Context, marshaler runtime.Marshaler, server UserServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
|
||||
var (
|
||||
protoReq LoginReq
|
||||
metadata runtime.ServerMetadata
|
||||
)
|
||||
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) {
|
||||
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
|
||||
}
|
||||
msg, err := server.Login(ctx, &protoReq)
|
||||
return msg, metadata, err
|
||||
}
|
||||
|
||||
// RegisterUserHandlerServer registers the http handlers for service User to "mux".
|
||||
// UnaryRPC :call UserServer directly.
|
||||
// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906.
|
||||
// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterUserHandlerFromEndpoint instead.
|
||||
// GRPC interceptors will not work for this type of registration. To use interceptors, you must use the "runtime.WithMiddlewares" option in the "runtime.NewServeMux" call.
|
||||
func RegisterUserHandlerServer(ctx context.Context, mux *runtime.ServeMux, server UserServer) error {
|
||||
mux.Handle(http.MethodPost, pattern_User_Login_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
|
||||
ctx, cancel := context.WithCancel(req.Context())
|
||||
defer cancel()
|
||||
var stream runtime.ServerTransportStream
|
||||
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
|
||||
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
|
||||
annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/.User/Login", runtime.WithHTTPPathPattern("/user/login"))
|
||||
if err != nil {
|
||||
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
|
||||
return
|
||||
}
|
||||
resp, md, err := local_request_User_Login_0(annotatedContext, inboundMarshaler, server, req, pathParams)
|
||||
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
|
||||
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
|
||||
if err != nil {
|
||||
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
|
||||
return
|
||||
}
|
||||
forward_User_Login_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// RegisterUserHandlerFromEndpoint is same as RegisterUserHandler but
|
||||
// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
|
||||
func RegisterUserHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {
|
||||
conn, err := grpc.NewClient(endpoint, opts...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
if cerr := conn.Close(); cerr != nil {
|
||||
grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr)
|
||||
}
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
if cerr := conn.Close(); cerr != nil {
|
||||
grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr)
|
||||
}
|
||||
}()
|
||||
}()
|
||||
return RegisterUserHandler(ctx, mux, conn)
|
||||
}
|
||||
|
||||
// RegisterUserHandler registers the http handlers for service User to "mux".
|
||||
// The handlers forward requests to the grpc endpoint over "conn".
|
||||
func RegisterUserHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
|
||||
return RegisterUserHandlerClient(ctx, mux, NewUserClient(conn))
|
||||
}
|
||||
|
||||
// RegisterUserHandlerClient registers the http handlers for service User
|
||||
// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "UserClient".
|
||||
// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "UserClient"
|
||||
// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in
|
||||
// "UserClient" to call the correct interceptors. This client ignores the HTTP middlewares.
|
||||
func RegisterUserHandlerClient(ctx context.Context, mux *runtime.ServeMux, client UserClient) error {
|
||||
mux.Handle(http.MethodPost, pattern_User_Login_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
|
||||
ctx, cancel := context.WithCancel(req.Context())
|
||||
defer cancel()
|
||||
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
|
||||
annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/.User/Login", runtime.WithHTTPPathPattern("/user/login"))
|
||||
if err != nil {
|
||||
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
|
||||
return
|
||||
}
|
||||
resp, md, err := request_User_Login_0(annotatedContext, inboundMarshaler, client, req, pathParams)
|
||||
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
|
||||
if err != nil {
|
||||
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
|
||||
return
|
||||
}
|
||||
forward_User_Login_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
var (
|
||||
pattern_User_Login_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"user", "login"}, ""))
|
||||
)
|
||||
|
||||
var (
|
||||
forward_User_Login_0 = runtime.ForwardResponseMessage
|
||||
)
|
||||
105
Server/common/proto/ss/grpc_pb/service_user_grpc.pb.go
Normal file
105
Server/common/proto/ss/grpc_pb/service_user_grpc.pb.go
Normal file
@@ -0,0 +1,105 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.2.0
|
||||
// - protoc v4.25.1
|
||||
// source: service_user.proto
|
||||
|
||||
package grpc_pb
|
||||
|
||||
import (
|
||||
context "context"
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the grpc package it is being compiled against.
|
||||
// Requires gRPC-Go v1.32.0 or later.
|
||||
const _ = grpc.SupportPackageIsVersion7
|
||||
|
||||
// UserClient is the client API for User service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
type UserClient interface {
|
||||
Login(ctx context.Context, in *LoginReq, opts ...grpc.CallOption) (*LoginResp, error)
|
||||
}
|
||||
|
||||
type userClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewUserClient(cc grpc.ClientConnInterface) UserClient {
|
||||
return &userClient{cc}
|
||||
}
|
||||
|
||||
func (c *userClient) Login(ctx context.Context, in *LoginReq, opts ...grpc.CallOption) (*LoginResp, error) {
|
||||
out := new(LoginResp)
|
||||
err := c.cc.Invoke(ctx, "/User/Login", in, out, opts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// UserServer is the server API for User service.
|
||||
// All implementations must embed UnimplementedUserServer
|
||||
// for forward compatibility
|
||||
type UserServer interface {
|
||||
Login(context.Context, *LoginReq) (*LoginResp, error)
|
||||
mustEmbedUnimplementedUserServer()
|
||||
}
|
||||
|
||||
// UnimplementedUserServer must be embedded to have forward compatible implementations.
|
||||
type UnimplementedUserServer struct {
|
||||
}
|
||||
|
||||
func (UnimplementedUserServer) Login(context.Context, *LoginReq) (*LoginResp, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method Login not implemented")
|
||||
}
|
||||
func (UnimplementedUserServer) mustEmbedUnimplementedUserServer() {}
|
||||
|
||||
// UnsafeUserServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to UserServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeUserServer interface {
|
||||
mustEmbedUnimplementedUserServer()
|
||||
}
|
||||
|
||||
func RegisterUserServer(s grpc.ServiceRegistrar, srv UserServer) {
|
||||
s.RegisterService(&User_ServiceDesc, srv)
|
||||
}
|
||||
|
||||
func _User_Login_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(LoginReq)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(UserServer).Login(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: "/User/Login",
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(UserServer).Login(ctx, req.(*LoginReq))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// User_ServiceDesc is the grpc.ServiceDesc for User service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
var User_ServiceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "User",
|
||||
HandlerType: (*UserServer)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "Login",
|
||||
Handler: _User_Login_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{},
|
||||
Metadata: "service_user.proto",
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -19,16 +20,89 @@ const (
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
type ErrorInfo struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
Code int32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"`
|
||||
Msg string `protobuf:"bytes,2,opt,name=msg,proto3" json:"msg,omitempty"`
|
||||
}
|
||||
|
||||
func (x *ErrorInfo) Reset() {
|
||||
*x = ErrorInfo{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_ss_common_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *ErrorInfo) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*ErrorInfo) ProtoMessage() {}
|
||||
|
||||
func (x *ErrorInfo) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_ss_common_proto_msgTypes[0]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use ErrorInfo.ProtoReflect.Descriptor instead.
|
||||
func (*ErrorInfo) Descriptor() ([]byte, []int) {
|
||||
return file_ss_common_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *ErrorInfo) GetCode() int32 {
|
||||
if x != nil {
|
||||
return x.Code
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *ErrorInfo) GetMsg() string {
|
||||
if x != nil {
|
||||
return x.Msg
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
var File_ss_common_proto protoreflect.FileDescriptor
|
||||
|
||||
var file_ss_common_proto_rawDesc = []byte{
|
||||
0x0a, 0x0f, 0x73, 0x73, 0x5f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74,
|
||||
0x6f, 0x42, 0x1b, 0x5a, 0x19, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x70, 0x72, 0x6f, 0x74,
|
||||
0x6f, 0x2f, 0x73, 0x73, 0x2f, 0x73, 0x73, 0x5f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x62, 0x06,
|
||||
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
|
||||
0x6f, 0x22, 0x31, 0x0a, 0x09, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x12,
|
||||
0x0a, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x04, 0x63, 0x6f,
|
||||
0x64, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x6d, 0x73, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52,
|
||||
0x03, 0x6d, 0x73, 0x67, 0x42, 0x1b, 0x5a, 0x19, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x70,
|
||||
0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x73, 0x73, 0x2f, 0x73, 0x73, 0x5f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f,
|
||||
0x6e, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
|
||||
}
|
||||
|
||||
var file_ss_common_proto_goTypes = []interface{}{}
|
||||
var (
|
||||
file_ss_common_proto_rawDescOnce sync.Once
|
||||
file_ss_common_proto_rawDescData = file_ss_common_proto_rawDesc
|
||||
)
|
||||
|
||||
func file_ss_common_proto_rawDescGZIP() []byte {
|
||||
file_ss_common_proto_rawDescOnce.Do(func() {
|
||||
file_ss_common_proto_rawDescData = protoimpl.X.CompressGZIP(file_ss_common_proto_rawDescData)
|
||||
})
|
||||
return file_ss_common_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_ss_common_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
|
||||
var file_ss_common_proto_goTypes = []interface{}{
|
||||
(*ErrorInfo)(nil), // 0: ErrorInfo
|
||||
}
|
||||
var file_ss_common_proto_depIdxs = []int32{
|
||||
0, // [0:0] is the sub-list for method output_type
|
||||
0, // [0:0] is the sub-list for method input_type
|
||||
@@ -42,18 +116,33 @@ func file_ss_common_proto_init() {
|
||||
if File_ss_common_proto != nil {
|
||||
return
|
||||
}
|
||||
if !protoimpl.UnsafeEnabled {
|
||||
file_ss_common_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*ErrorInfo); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: file_ss_common_proto_rawDesc,
|
||||
NumEnums: 0,
|
||||
NumMessages: 0,
|
||||
NumMessages: 1,
|
||||
NumExtensions: 0,
|
||||
NumServices: 0,
|
||||
},
|
||||
GoTypes: file_ss_common_proto_goTypes,
|
||||
DependencyIndexes: file_ss_common_proto_depIdxs,
|
||||
MessageInfos: file_ss_common_proto_msgTypes,
|
||||
}.Build()
|
||||
File_ss_common_proto = out.File
|
||||
file_ss_common_proto_rawDesc = nil
|
||||
|
||||
Reference in New Issue
Block a user