├── 1.png
├── 2.png
├── 3.png
├── .gitignore
├── api
└── thrift
│ ├── gen-go
│ └── rpc
│ │ ├── GoUnusedProtection__.go
│ │ ├── user-consts.go
│ │ ├── user_service-remote
│ │ └── user_service-remote.go
│ │ └── user.go
│ └── user.thrift
├── invest
├── common
│ ├── game_status.go
│ ├── message.go
│ ├── model.go
│ ├── tools.go
│ ├── config.go
│ └── init.go
├── tools
│ ├── tools.go
│ ├── call_rpc.go
│ └── aes.go
├── router
│ └── router.go
├── main
│ ├── main.go
│ ├── init.go
│ └── config.go
├── service
│ ├── service.go
│ ├── message.go
│ ├── request.go
│ ├── client.go
│ ├── hub.go
│ └── room.go
├── conf
│ └── app.conf
├── controllers
│ └── invest
│ │ ├── register.go
│ │ ├── get_uer_info.go
│ │ ├── record_list.go
│ │ ├── stake.go
│ │ ├── record_detail.go
│ │ └── reward_record.go
└── logic
│ └── invest
│ ├── calculate.go
│ ├── record.go
│ └── main.go
├── account
├── service
│ ├── main.go
│ └── handle.go
├── common
│ ├── config.go
│ └── checkToken.go
├── conf
│ └── app.conf
└── main
│ ├── main.go
│ ├── init.go
│ └── config.go
├── back
├── main
│ ├── main.go
│ ├── config.go
│ └── init.go
├── conf
│ └── app.conf
└── service
│ └── main.go
├── README.md
├── game.sql
└── ws.html
/1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dwg255/invest/HEAD/1.png
--------------------------------------------------------------------------------
/2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dwg255/invest/HEAD/2.png
--------------------------------------------------------------------------------
/3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dwg255/invest/HEAD/3.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea/
2 | account/logs/
3 | invest/logs/
4 | *.exe
5 | *.exe~
--------------------------------------------------------------------------------
/api/thrift/gen-go/rpc/GoUnusedProtection__.go:
--------------------------------------------------------------------------------
1 | // Autogenerated by Thrift Compiler (0.11.0)
2 | // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
3 |
4 | package rpc
5 |
6 | var GoUnusedProtection__ int;
7 |
8 |
--------------------------------------------------------------------------------
/invest/common/game_status.go:
--------------------------------------------------------------------------------
1 | package common
2 |
3 | const (
4 | StatusPrepare = iota
5 | StatusStartStake
6 | StatusSendStake
7 | StatusEndStake
8 | StatusSendResult //下发结果
9 | StatusShowResult
10 | StatusShowWinGold
11 | )
12 |
--------------------------------------------------------------------------------
/account/service/main.go:
--------------------------------------------------------------------------------
1 | package service
2 |
3 | import "game/account/common"
4 | var(
5 | userServiceConf *common.UserServiceConf
6 | )
7 | func InitService(UserServiceConf *common.UserServiceConf) {
8 | userServiceConf = UserServiceConf
9 | }
10 | type UserServer struct {
11 |
12 | }
--------------------------------------------------------------------------------
/invest/tools/tools.go:
--------------------------------------------------------------------------------
1 | package tools
2 |
3 | import (
4 | "crypto/md5"
5 | "fmt"
6 | "time"
7 | "io"
8 | )
9 |
10 | func CreateUid() (uuid string) {
11 | t := time.Now()
12 | h := md5.New()
13 | io.WriteString(h, "crazyof.me")
14 | io.WriteString(h, t.String())
15 | uuid = fmt.Sprintf("%x", h.Sum(nil))
16 | return
17 | }
--------------------------------------------------------------------------------
/back/main/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "github.com/astaxie/beego/logs"
5 | )
6 |
7 | func main() {
8 | err := initConf()
9 | if err != nil {
10 | logs.Error("init conf err:%v",err)
11 | return
12 | }
13 |
14 | err = initSec()
15 | if err != nil {
16 | logs.Error("init sec err:%v",err)
17 | return
18 | }
19 | }
--------------------------------------------------------------------------------
/back/conf/app.conf:
--------------------------------------------------------------------------------
1 | #[dev]
2 |
3 | ;redis相关配置
4 | redis_addr=127.0.0.1:6379
5 | redis_max_idle = 64
6 | redis_max_active = 0
7 | redis_idle_timeout = 300
8 |
9 | ;相关key
10 | redis_key_user_stake_msg=invest_user_stake
11 | redis_key_invest_base=invest_base
12 |
13 | ;日志相关配置
14 | log_path=./logs/back.log
15 | log_level=debug
16 |
17 | ;mysql 相关配置
18 | mysql_addr=127.0.0.1:3306
19 | mysql_user=root
20 | mysql_password=root
21 | mysql_db=game
--------------------------------------------------------------------------------
/account/common/config.go:
--------------------------------------------------------------------------------
1 | package common
2 |
3 | import "github.com/garyburd/redigo/redis"
4 |
5 |
6 | type UserServiceConf struct {
7 | ThriftPort int
8 | RedisConf RedisConf
9 | LogPath string
10 | LogLevel string
11 | AppSecret string
12 | UserRedisPrefix string
13 | }
14 |
15 | type RedisConf struct {
16 | RedisAddr string
17 | RedisMaxIdle int
18 | RedisMaxActive int
19 | RedisIdleTimeout int
20 | RedisPool *redis.Pool
21 | }
22 |
--------------------------------------------------------------------------------
/account/conf/app.conf:
--------------------------------------------------------------------------------
1 | #[dev]
2 |
3 | ;redis相关配置
4 | redis_addr=127.0.0.1:6379
5 | redis_max_idle = 64
6 | redis_max_active = 0
7 | redis_idle_timeout = 300
8 |
9 | ;日志相关配置
10 | log_path=./logs/game.log
11 | log_level=debug
12 |
13 | ;mysql 相关配置
14 | mysql_addr=127.0.0.1:3306
15 | mysql_user=root
16 | mysql_password=root
17 | mysql_db=game
18 |
19 | ;密钥
20 | app_secret=a26fe778a427b45901dc2a9f198c4f57
21 |
22 | ;rpc 端口
23 | thrift_port=8989
24 |
25 | ;redis key
26 | user_redis_prefix=invest_user_
--------------------------------------------------------------------------------
/api/thrift/gen-go/rpc/user-consts.go:
--------------------------------------------------------------------------------
1 | // Autogenerated by Thrift Compiler (0.11.0)
2 | // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
3 |
4 | package rpc
5 |
6 | import (
7 | "bytes"
8 | "reflect"
9 | "context"
10 | "fmt"
11 | "git.apache.org/thrift.git/lib/go/thrift"
12 | )
13 |
14 | // (needed to ensure safety because of naive import list construction.)
15 | var _ = thrift.ZERO
16 | var _ = fmt.Printf
17 | var _ = context.Background
18 | var _ = reflect.DeepEqual
19 | var _ = bytes.Equal
20 |
21 |
22 | func init() {
23 | }
24 |
25 |
--------------------------------------------------------------------------------
/invest/router/router.go:
--------------------------------------------------------------------------------
1 | package router
2 |
3 | import (
4 | "net/http"
5 | "game/invest/service"
6 | "game/invest/controllers/invest"
7 | )
8 |
9 | func init() {
10 | http.HandleFunc("/api/user/getUserInfo", invest.GetUserInfo)
11 |
12 | http.HandleFunc("/api/invest/register", invest.Register)
13 | http.HandleFunc("/api/invest/stake", invest.Stake)
14 | http.HandleFunc("/api/invest/rewardRecord",invest.RewardRecord)
15 | http.HandleFunc("/api/invest/recordList",invest.RecordList)
16 | http.HandleFunc("/api/invest/recordDetail",invest.RecordDetail)
17 |
18 | http.HandleFunc("/",service.ServeWs)
19 | }
20 |
--------------------------------------------------------------------------------
/invest/main/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "net/http"
5 | "flag"
6 | "fmt"
7 | "github.com/astaxie/beego/logs"
8 | _"game/invest/router"
9 | )
10 |
11 | func main() {
12 | err := initConf()
13 | if err != nil {
14 | logs.Error("init conf err:%v",err)
15 | return
16 | }
17 |
18 | err = initSec()
19 | if err != nil {
20 | logs.Error("init sec err:%v",err)
21 | return
22 | }
23 |
24 | var addr = flag.String("addr", fmt.Sprintf(":%d",gameConf.HttpPort), "http service address")
25 |
26 | err = http.ListenAndServe(*addr, nil)
27 | if err != nil {
28 | logs.Error("ListenAndServe: err:%v", err)
29 | }
30 | }
--------------------------------------------------------------------------------
/invest/service/service.go:
--------------------------------------------------------------------------------
1 | package service
2 |
3 | import (
4 | "github.com/astaxie/beego/logs"
5 | "game/invest/logic/invest"
6 | "game/invest/common"
7 | )
8 |
9 | var (
10 | GameConf *common.GameConf
11 | HubMgr *Hub
12 | )
13 |
14 | func InitService(serviceConf *common.GameConf) {
15 | GameConf = serviceConf
16 | var err error
17 | HubMgr, err = NewHub()
18 | if err != nil {
19 | logs.Error("new newHub err :%v", err)
20 | panic("new newHub err ")
21 | }
22 | go HubMgr.run()
23 | go HubMgr.broadcast()
24 | HubMgr.GameInfo, HubMgr.GameManage = invest.InitInvest(HubMgr.CenterCommandChan, GameConf)
25 | go invest.RunLogic()
26 | logs.Debug("init service succ")
27 | }
28 |
29 |
--------------------------------------------------------------------------------
/invest/conf/app.conf:
--------------------------------------------------------------------------------
1 | #[dev]
2 |
3 | http_port=8080
4 |
5 | ;redis相关配置
6 | redis_addr=127.0.0.1:6379
7 | redis_max_idle = 64
8 | redis_max_active = 0
9 | redis_idle_timeout = 300
10 |
11 | ;相关key
12 | redis_key_user_stake_msg=invest_user_stake
13 | redis_key_invest_base=invest_base
14 |
15 | ;日志相关配置
16 | log_path=./logs/game.log
17 | log_level=debug
18 |
19 | ;etcd 相关配置
20 | etcd_addr=127.0.0.1:2379
21 | etcd_timeout = 5
22 | etcd_sec_key_prefix=/seckill
23 | etcd_product_key=product
24 |
25 |
26 | ;密钥
27 | app_secret=a26fe778a427b45901dc2a9f198c4f57
28 |
29 | pumping_rate=0
30 |
31 | ;rpc 端口
32 | thrift_port=:8989
33 |
34 | ;mysql 相关配置
35 | mysql_addr=127.0.0.1:3306
36 | mysql_user=root
37 | mysql_password=root
38 | mysql_db=game
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # game
2 | golang开发的h5小游戏 [服务端] domo
3 |
4 | #### 软件架构
5 | account 模块提供用户注册、验证、扣费thrift rpc服务
6 |
7 | invest 模块处理前台http、websocket请求,启动定时器更替游戏状态。前台hub层处理用户登录退出,room层处理房间消息推送、结算。watch etcd进行服务器降级(暂无)
8 |
9 | back 模块将数据持久化到mysql
10 |
11 | #### 安装方式
12 | 1. 切换到在GOPATH目录下
13 | 2. git clone https://github.com/dwg255/invest.git
14 | 3. 编译帐号服务 go build -o game/account/account game/account/main
15 | 4. 编译逻辑服务 go build -o game/invest/invest game/invest/main
16 | 5. 编译持久化服务 go build -o game/back/back game/back/main
17 | 6. 启动全部
18 | 7. 简易调试demo ws.html
19 |
20 | #### 示例链接
21 | http://invest.blzz.shop/login/
22 |
23 | 
24 | 
25 | 
26 |
--------------------------------------------------------------------------------
/invest/common/message.go:
--------------------------------------------------------------------------------
1 | package common
2 |
3 | import "sync"
4 |
5 | type Message struct {
6 | Type int
7 | Timer int
8 | }
9 |
10 | type GameInfo struct {
11 | StakeMap map[int]int
12 | Lock sync.RWMutex
13 | GameResult *InvestConf
14 | Pool int //奖池
15 | Periods int
16 | }
17 |
18 | type Record struct {
19 | ResultChan chan *InvestConf
20 | LasTTenTimesRank [10]*GameRank
21 | ContinuedWinRecord map[*InvestConf]int //连续赢的位置
22 | LastTimeWinRecord map[int]int //距离上一次赢的局数
23 | UnfortunatelyRecord *UnfortunatelyPosition
24 | EverydayResultRecord *EveryDayRecord
25 | Lock sync.RWMutex
26 | }
27 |
28 | type GameRank struct {
29 | Periods string `json:"periods"`
30 | GameResult *InvestConf `json:"game_result"`
31 | }
32 |
33 | //最不幸的位置和连续不出记录
34 | type UnfortunatelyPosition struct {
35 | Position int
36 | Count int
37 | }
38 |
39 | type EveryDayRecord struct {
40 | Date string
41 | Record map[*InvestConf]int
42 | }
43 |
--------------------------------------------------------------------------------
/account/main/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "game/api/thrift/gen-go/rpc"
5 | "git.apache.org/thrift.git/lib/go/thrift"
6 | "github.com/astaxie/beego/logs"
7 | "fmt"
8 | "game/account/service"
9 | )
10 |
11 | func main() {
12 | err := initConf()
13 | if err != nil {
14 | logs.Error("init conf err:%v",err)
15 | return
16 | }
17 | err = initSec()
18 | if err != nil {
19 | logs.Error("initSec err:%v",err)
20 | return
21 | }
22 |
23 | port := fmt.Sprintf(":%d",UserServiceConf.ThriftPort)
24 | transport, err := thrift.NewTServerSocket(port)
25 | if err != nil {
26 | panic(err)
27 | }
28 | handler := &service.UserServer{}
29 | processor := rpc.NewUserServiceProcessor(handler)
30 |
31 | transportFactory := thrift.NewTBufferedTransportFactory(8192)
32 | protocolFactory := thrift.NewTCompactProtocolFactory()
33 |
34 | server := thrift.NewTSimpleServer4(
35 | processor,
36 | transport,
37 | transportFactory,
38 | protocolFactory,
39 | )
40 |
41 | if err := server.Serve(); err != nil {
42 | panic(err)
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/api/thrift/user.thrift:
--------------------------------------------------------------------------------
1 | namespace go rpc
2 |
3 | enum ErrorCode{
4 | Success=0
5 | UnknowError=5000,
6 | VerifyError=5001,
7 | UserIsNull=5002,
8 | AddUserFail=5005,
9 | UserBeKickOff=5006,
10 | GoldNotEnough=5007,
11 | DiamondNotEnough=5009,
12 | }
13 |
14 | struct UserInfo{
15 | 1: i64 userId
16 | 2: string userName
17 | 3: string nickName
18 | 4: string avatarAuto
19 | 5: i64 gold //游戏金币
20 | 6: string token
21 | }
22 |
23 | struct Result{
24 | 1: ErrorCode code
25 | 2: UserInfo user_obj
26 | }
27 |
28 | service UserService {
29 |
30 | Result createNewUser(1: string nickName 2:string avatarAuto 3: i64 gold )//初始金币
31 |
32 | //获取用户信息 BY userId
33 | Result getUserInfoById(1:i32 userId)
34 |
35 | //获取用户信息 BY token
36 | Result getUserInfoByken(1:string token)
37 |
38 | //修改用户金币
39 | Result modifyGoldById(1:string behavior, 2:i32 userId, 3:i64 gold)
40 | Result modifyGoldByToken(1:string behavior, 2:string token,3:i64 gold)
41 | }
42 |
--------------------------------------------------------------------------------
/invest/service/message.go:
--------------------------------------------------------------------------------
1 | package service
2 |
3 | type Message struct {
4 | Act string `json:"act"`
5 | State string `json:"state"`
6 | //WinResult int `json:"win_result"`
7 | WinPosition []int `json:"win_position"`
8 | Pool int `json:"pool"`
9 | MaxContinueLostPosition int `json:"max_continue_lost_position"`
10 | MaxContinueLostCount int `json:"max_continue_lost_count"`
11 | Timer int `json:"timer"`
12 | Periods int `json:"periods"`
13 | NewStake map[string]map[string]int `json:"new_stake"`
14 | StakeInfo []map[string]int `json:"stake_info"`
15 | UserWinResult []*UserWinResult `json:"win_result"`
16 | }
17 |
18 | type UserWinResult struct {
19 | UserId UserId `json:"user_id"`
20 | WinGold int `json:"win_gold"`
21 | }
22 |
--------------------------------------------------------------------------------
/invest/tools/call_rpc.go:
--------------------------------------------------------------------------------
1 | package tools
2 |
3 | import (
4 | "git.apache.org/thrift.git/lib/go/thrift"
5 | "fmt"
6 | "game/api/thrift/gen-go/rpc"
7 | "net"
8 | )
9 |
10 | func GetRpcClient() (client *rpc.UserServiceClient, closeTransport func() error, err error) {
11 | var transport thrift.TTransport
12 | transport, err = thrift.NewTSocket(net.JoinHostPort("127.0.0.1", "8989"))
13 | if err != nil {
14 | fmt.Errorf("NewTSocket failed. err: [%v]\n", err)
15 | return
16 | }
17 |
18 | transport, err = thrift.NewTBufferedTransportFactory(8192).GetTransport(transport)
19 | if err != nil {
20 | fmt.Errorf("NewTransport failed. err: [%v]\n", err)
21 | return
22 | }
23 | closeTransport = transport.Close
24 |
25 | if err = transport.Open(); err != nil {
26 | fmt.Errorf("Transport.Open failed. err: [%v]\n", err)
27 | return
28 | }
29 | protocolFactory := thrift.NewTCompactProtocolFactory()
30 | iprot := protocolFactory.GetProtocol(transport)
31 | oprot := protocolFactory.GetProtocol(transport)
32 | client = rpc.NewUserServiceClient(thrift.NewTStandardClient(iprot, oprot))
33 | return
34 | }
35 |
--------------------------------------------------------------------------------
/invest/common/model.go:
--------------------------------------------------------------------------------
1 | package common
2 |
3 | type InvestBase struct {
4 | Id int `json:"id"`
5 | GameTimesId string `json:"game_times_id"`
6 | Periods int `json:"periods"`
7 | Pool int `json:"game_pool"`
8 | GameResult int `json:"game_result"`
9 | StakeDetail string `json:"stake_detail"`
10 | StartTime string `json:"start_time"`
11 | }
12 |
13 | type InvestUserStake struct {
14 | Id int `json:"id" db:"id"`
15 | GameTimesId string `json:"game_times_id" db:"game_times_id"`
16 | Periods int `json:"record_id" db:"periods"`
17 | RoomId int `json:"room_id" db:"room_id"`
18 | RoomType int `json:"room_type" db:"room_type"`
19 | UserId int `json:"user_id" db:"user_id"`
20 | Nickname string `json:"nickname" db:"nickname"`
21 | UserAllStake int `json:"stake_gold" db:"user_all_stake"`
22 | WinGold int `json:"get_gold" db:"get_gold"`
23 | StakeDetail string `json:"stake_detail" db:"stake_detail"`
24 | GameResult int `json:"game_result" db:"game_result"`
25 | Pool int `json:"game_pool" db:"game_pool"`
26 | StakeTime string `json:"stake_time" db:"last_stake_time"`
27 | }
28 |
--------------------------------------------------------------------------------
/account/common/checkToken.go:
--------------------------------------------------------------------------------
1 | package common
2 |
3 | import (
4 | "strings"
5 | "strconv"
6 | "github.com/astaxie/beego/logs"
7 | "game/invest/tools"
8 | "fmt"
9 | "time"
10 | "net/url"
11 | )
12 |
13 | var(
14 | AesTool *tools.AesEncrypt
15 | )
16 | func init() {
17 | var err error
18 | AesTool,err = tools.NewAesTool("a26fe778a427b45901dc2a9f198c4f57")
19 | if err != nil {
20 | msg := fmt.Sprintf("init aestool failed,err:%v",err)
21 | panic(msg)
22 | }
23 | }
24 | func CheckToken(token string) (userId int,err error) {
25 | token, _=url.QueryUnescape(token)
26 | token = strings.Replace(token," ","+",-1)
27 | identity,err := AesTool.Decrypt(token)
28 | if err != nil {
29 | logs.Error("token [%s] decrypt err:%v",token,err)
30 | return
31 | }
32 | //logs.Debug("decrypt identity :%s",identity)
33 |
34 | data := strings.Split(identity,"|")
35 | if len(data) == 2 {
36 | userId,err = strconv.Atoi(data[0])
37 | if err != nil {
38 | logs.Error("userid [%s] sting to int err:%v",data[0],err)
39 | return
40 | }
41 | return
42 | } else {
43 | err = fmt.Errorf("check token [%s] failed",token)
44 | }
45 | return
46 | }
47 |
48 | func CreateToken(userId int64) (token string,err error) {
49 | identity := fmt.Sprintf("%d|%d",userId,time.Now().Unix())
50 | token,err = AesTool.Encrypt(identity)
51 | return
52 | }
--------------------------------------------------------------------------------
/invest/controllers/invest/register.go:
--------------------------------------------------------------------------------
1 | package invest
2 |
3 | import (
4 | "net/http"
5 | "github.com/astaxie/beego/logs"
6 | "game/invest/tools"
7 | "golang.org/x/net/context"
8 | "game/api/thrift/gen-go/rpc"
9 | "time"
10 | "math/rand"
11 | "fmt"
12 | )
13 |
14 | func Register(w http.ResponseWriter, r *http.Request) {
15 | defer func() {
16 | if r:= recover(); r != nil {
17 | logs.Error("Register panic:%v ",r)
18 | }
19 | }()
20 |
21 | nickname := r.FormValue("nickname")
22 | if len(nickname) == 0 {
23 | nickname = r.PostFormValue("nickname")
24 | }
25 | rpcClient, closeTransport, err := tools.GetRpcClient()
26 | if err != nil {
27 | logs.Debug("get rpc client err:%v", err)
28 | return
29 | }
30 | defer closeTransport()
31 |
32 | rand.Seed(time.Now().UnixNano())
33 | pic := rand.Intn(34) + 1
34 | picName := fmt.Sprintf("http://182.61.24.31:81/%d.jpg",pic)
35 | resp, err := rpcClient.CreateNewUser(context.Background(), nickname,picName,100000)
36 | //logs.Debug("user info %v",resp)
37 | if err != nil || resp.Code != rpc.ErrorCode_Success {
38 | logs.Debug("create user failed err:%v, resp:%v", err, resp)
39 | } else {
40 | url := "http://182.61.24.31?token=" + resp.UserObj.Token
41 | //url := "http://invest.com/index.html?token=" + resp.UserObj.Token
42 | http.Redirect(w, r, url, http.StatusFound)
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/invest/common/tools.go:
--------------------------------------------------------------------------------
1 | package common
2 |
3 | import "github.com/astaxie/beego/logs"
4 |
5 | //优化,保存父级,不用每次都计算
6 | func (p *InvestConf) GetParents() (parentArr []*InvestConf) {
7 | return p.ParentArr
8 | }
9 |
10 | func (p *InvestConf) InitParents() (parentArr []*InvestConf ,ok bool) {
11 | parentArr = append(parentArr, p)
12 | for parentInvestConf, hasFather := p.GetFather(); hasFather; {
13 | parentArr = append(parentArr, parentInvestConf)
14 | parentInvestConf, hasFather = parentInvestConf.GetFather()
15 | }
16 | p.ParentArr = parentArr
17 | if len(p.ParentArr) > 0 {
18 | ok = true
19 | }
20 | return
21 | }
22 |
23 | func (p *InvestConf) GetFather() (parentInvestConf *InvestConf, hasFather bool) {
24 | if p.ParentId == 0 {
25 | return
26 | }
27 | for _, investConf := range InvestConfArr {
28 | if investConf.Id == p.ParentId {
29 | parentInvestConf, hasFather = investConf, true
30 | return
31 | }
32 | }
33 | return
34 | }
35 |
36 | func (p *InvestConf) GetNeedGold(StakeMap map[int]int) (needGold int) {
37 | winPositionArr := p.GetParents()
38 | for _,investConf := range winPositionArr{
39 | stakeGold,ok := StakeMap[investConf.Id]
40 | if !ok {
41 | logs.Error("user total stake in [%d] is nil",investConf.Id)
42 | continue
43 | }
44 | needGold = needGold + int(float32(stakeGold) * investConf.Rate)
45 | }
46 | return
47 | }
--------------------------------------------------------------------------------
/invest/common/config.go:
--------------------------------------------------------------------------------
1 | package common
2 |
3 | import (
4 | "github.com/garyburd/redigo/redis"
5 | etcd_client "github.com/coreos/etcd/clientv3"
6 | "sync"
7 | "github.com/jmoiron/sqlx"
8 | )
9 |
10 | type GameConf struct {
11 | HttpPort int
12 | RedisConf RedisConf
13 | RedisKey RedisKey
14 | EtcdConf EtcdConf
15 | LogPath string
16 | LogLevel string
17 | AppSecret string
18 | PumpingRate int //抽水率,百分之几
19 | MysqlConf MysqlConf
20 | //RwBlackLock sync.RWMutex
21 | }
22 |
23 | type MysqlConf struct {
24 | MysqlAddr string
25 | MysqlUser string
26 | MysqlPassword string
27 | MysqlDatabase string
28 | Pool *sqlx.DB
29 | }
30 |
31 | type RedisConf struct {
32 | RedisAddr string
33 | RedisMaxIdle int
34 | RedisMaxActive int
35 | RedisIdleTimeout int
36 | RedisPool *redis.Pool
37 | }
38 |
39 | type RedisKey struct {
40 | RedisKeyUserStake string
41 | RedisKeyInvestBase string
42 | }
43 |
44 | type EtcdConf struct {
45 | EtcdAddr string
46 | Timeout int
47 | //EtcdSecKeyPrefix string
48 | //EtcdSecProductKey string
49 | EtcdClient *etcd_client.Client
50 | }
51 |
52 | type CanStakeChip struct {
53 | GoldMin int64
54 | GoldMax int64
55 | Chips [3]int
56 | }
57 |
58 | type GameManage struct {
59 | Periods int //设置期数id 自增
60 | GameStatus int //游戏状态
61 | Timer int //当局秒数
62 | StakeCountdown int //押注倒计时
63 | SendTime int //本局已发送押注的次数
64 | TimesId string //场次id 唯一字符串 期数是循环的,timesId作为唯一标识
65 | Lock sync.RWMutex
66 | }
67 |
68 | type InvestConf struct {
69 | Id int `json:"id"`
70 | Name string `json:"name"`
71 | ParentId int `json:"parent_id"`
72 | Rate float32 `json:"rate"`
73 | Weight int `json:"weight"`
74 | Icon string `json:"icon"`
75 | ParentArr []*InvestConf `json:"-"`
76 | WinPosition []int `json:"-"`
77 | }
78 |
--------------------------------------------------------------------------------
/invest/controllers/invest/get_uer_info.go:
--------------------------------------------------------------------------------
1 | package invest
2 |
3 | import (
4 | "net/http"
5 | "github.com/astaxie/beego/logs"
6 | "game/invest/tools"
7 | "golang.org/x/net/context"
8 | "encoding/json"
9 | "game/api/thrift/gen-go/rpc"
10 | "time"
11 | "game/invest/common"
12 | )
13 |
14 | func GetUserInfo(w http.ResponseWriter, r *http.Request) {
15 | defer func() {
16 | if r:= recover(); r != nil {
17 | logs.Error("GetUserInfo panic:%v ",r)
18 | }
19 | }()
20 | //logs.Debug("new request url:[%s]",r.URL)
21 | ret := make(map[string]interface{})
22 | ret["time"] = time.Now().Format("2006-01-02 15:04:05")
23 | defer func() {
24 | data, err := json.Marshal(ret)
25 | if err != nil {
26 | logs.Error("json marsha1 failed err:%v", err)
27 | return
28 | }
29 | w.Header().Set("Access-Control-Allow-Origin", "*")
30 | w.Write(data)
31 | }()
32 |
33 | token := r.FormValue("token")
34 | if len(token) == 0 {
35 | token = r.PostFormValue("token")
36 | }
37 | rpcClient, closeTransport, err := tools.GetRpcClient()
38 | if err != nil {
39 | logs.Debug("get rpc client err:%v", err)
40 | ret["code"] = common.ErrorRpcServerError
41 | return
42 | }
43 | defer closeTransport()
44 |
45 | resp, err := rpcClient.GetUserInfoByken(context.Background(), token)
46 | //logs.Debug("user info %v",resp)
47 | if err != nil || resp.Code != rpc.ErrorCode_Success {
48 | logs.Debug("check user token [%v] failed err:%v, resp:%v", token, err, resp)
49 | ret["code"] = common.ErrorAuthFailed
50 | } else {
51 | ret["code"] = int(resp.Code)
52 | identityObj := map[string]interface{}{
53 | "userId": resp.UserObj.UserId,
54 | "nickName": resp.UserObj.NickName,
55 | "avatarAuto": resp.UserObj.AvatarAuto,
56 | "sex": 1,
57 | "gold": resp.UserObj.Gold,
58 | "goldenBean": resp.UserObj.Gold,
59 | "diamond": 100000,
60 | "level": 12,
61 | "vipLevel": 1,
62 | }
63 | ret["result"] = map[string]interface{}{
64 | "identity_obj": identityObj,
65 | }
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/account/main/init.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "github.com/astaxie/beego/logs"
5 | "github.com/garyburd/redigo/redis"
6 | "time"
7 | "fmt"
8 | "encoding/json"
9 | "game/account/service"
10 | )
11 |
12 | //var (
13 | // redisPool *redis.Pool
14 | // etcdClient *etcd_client.Client
15 | //)
16 |
17 | func initRedis() (err error) {
18 | UserServiceConf.RedisConf.RedisPool = &redis.Pool{
19 | MaxIdle: UserServiceConf.RedisConf.RedisMaxIdle,
20 | MaxActive:UserServiceConf.RedisConf.RedisMaxActive,
21 | IdleTimeout:time.Duration(UserServiceConf.RedisConf.RedisIdleTimeout) * time.Second,
22 | Dial: func() (redis.Conn ,error) {
23 | return redis.Dial("tcp",UserServiceConf.RedisConf.RedisAddr)
24 | },
25 | }
26 | conn := UserServiceConf.RedisConf.RedisPool.Get()
27 | defer conn.Close()
28 | //defer UserServiceConf.RedisConf.RedisPool.Close()
29 | _,err = conn.Do("ping")
30 | if err != nil {
31 | logs.Error("ping redis failed,err:%v",err)
32 | return
33 | }
34 | return
35 | }
36 |
37 | func converLogLevel(logLevel string) int {
38 | switch logLevel {
39 | case "debug":
40 | return logs.LevelDebug
41 | case "warn":
42 | return logs.LevelWarn
43 | case "info":
44 | return logs.LevelInfo
45 | case "trace":
46 | return logs.LevelTrace
47 | }
48 | return logs.LevelDebug
49 | }
50 | func initLogger() (err error) {
51 | config := make(map[string]interface{})
52 | config["filename"] = UserServiceConf.LogPath
53 | config["level"] = converLogLevel(UserServiceConf.LogLevel)
54 |
55 | configStr,err := json.Marshal(config)
56 | if err != nil {
57 | fmt.Println("marsha1 faild,err",err)
58 | return
59 | }
60 | logs.SetLogger(logs.AdapterFile,string(configStr))
61 | return
62 | }
63 |
64 |
65 | func initSec() (err error) {
66 | err = initLogger()
67 | if err != nil {
68 | logs.Error("init logger failed,err:%v",err)
69 | return
70 | }
71 | err = initRedis()
72 | if err != nil {
73 | logs.Error("init redis failed,err :%v",err)
74 | return
75 | }
76 |
77 | service.InitService(UserServiceConf)
78 | logs.Info("init sec succ")
79 | return
80 | }
81 |
82 |
--------------------------------------------------------------------------------
/account/main/config.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "github.com/astaxie/beego"
5 | "github.com/astaxie/beego/logs"
6 | "fmt"
7 | "game/account/common"
8 | )
9 |
10 | var (
11 | UserServiceConf = &common.UserServiceConf{}
12 | )
13 |
14 | func initConf() (err error) {
15 | UserServiceConf.ThriftPort,err = beego.AppConfig.Int("thrift_port")
16 | if err != nil {
17 | logs.Error("init http_port failed,err:%v",err)
18 | return
19 | }
20 | logs.Debug("read conf succ,http port %v", UserServiceConf.ThriftPort)
21 |
22 | //todo redis相关配置
23 | UserServiceConf.RedisConf.RedisAddr = beego.AppConfig.String("redis_addr")
24 | if len(UserServiceConf.RedisConf.RedisAddr) == 0 {
25 | err = fmt.Errorf("init config failed, http_addr [%s]", UserServiceConf.RedisConf.RedisAddr)
26 | return
27 | }
28 |
29 | UserServiceConf.RedisConf.RedisAddr = beego.AppConfig.String("redis_addr")
30 | if len(UserServiceConf.RedisConf.RedisAddr) == 0 {
31 | err = fmt.Errorf("init config failed, redis_addr [%s]", UserServiceConf.RedisConf.RedisAddr)
32 | return
33 | }
34 | UserServiceConf.RedisConf.RedisMaxIdle,err = beego.AppConfig.Int("redis_max_idle")
35 | if err != nil {
36 | logs.Error("init config failed,read redis_max_idle err :%v", err)
37 | return
38 | }
39 | UserServiceConf.RedisConf.RedisMaxActive, err = beego.AppConfig.Int("redis_max_active")
40 | if err != nil {
41 | logs.Error("init config failed,read redis_max_active err :%v", err)
42 | return
43 | }
44 | UserServiceConf.RedisConf.RedisIdleTimeout, err = beego.AppConfig.Int("redis_idle_timeout")
45 | if err != nil {
46 | logs.Error("init config failed,read redis_idle_timeout err :%v", err)
47 | return
48 | }
49 |
50 | //todo 工程密钥
51 | UserServiceConf.AppSecret = beego.AppConfig.String("app_secret")
52 | if len(UserServiceConf.AppSecret) == 0 {
53 | err = fmt.Errorf("init config failed, app_secret [%s]", UserServiceConf.AppSecret)
54 | return
55 | }
56 |
57 | //todo 日志配置
58 | UserServiceConf.LogPath = beego.AppConfig.String("log_path")
59 | UserServiceConf.LogPath = beego.AppConfig.String("log_path")
60 | UserServiceConf.UserRedisPrefix = beego.AppConfig.String("user_redis_prefix")
61 |
62 | return
63 | }
64 |
--------------------------------------------------------------------------------
/invest/tools/aes.go:
--------------------------------------------------------------------------------
1 | package tools
2 |
3 | import (
4 | "crypto/aes"
5 | "crypto/cipher"
6 | "fmt"
7 | "encoding/hex"
8 | )
9 |
10 | func NewAesTool(appSecret string) (aesTool *AesEncrypt,err error) {
11 | if len(appSecret) <16 {
12 | err = fmt.Errorf("invalid param appsecret of %s",appSecret)
13 | return
14 | }
15 | aesTool = &AesEncrypt{AppSecret:appSecret}
16 | return
17 | }
18 |
19 | type AesEncrypt struct {
20 | AppSecret string
21 | }
22 |
23 | func (p *AesEncrypt) getKey() []byte {
24 | strKey := p.AppSecret
25 | keyLen := len(strKey)
26 | if keyLen < 16 {
27 | panic("res key 长度不能小于16")
28 | }
29 | arrKey := []byte(strKey)
30 | if keyLen >= 32 {
31 | //取前32个字节
32 | return arrKey[:32]
33 | }
34 | if keyLen >= 24 {
35 | //取前24个字节
36 | return arrKey[:24]
37 | }
38 | //取前16个字节
39 | return arrKey[:16]
40 | }
41 |
42 | //加密字符串
43 | func (p *AesEncrypt) Encrypt(strMesg string) (string, error) {
44 | key := p.getKey()
45 | var iv = []byte(key)[:aes.BlockSize]
46 | encrypted := make([]byte, len(strMesg))
47 | aesBlockEncrypter, err := aes.NewCipher(key)
48 | if err != nil {
49 | return "", err
50 | }
51 | aesEncrypter := cipher.NewCFBEncrypter(aesBlockEncrypter, iv)
52 | aesEncrypter.XORKeyStream(encrypted, []byte(strMesg))
53 | encodeString := fmt.Sprintf("%x",encrypted)
54 | //encodeString := base64.StdEncoding.EncodeToString([]byte(encrypted))
55 | return encodeString, nil
56 | }
57 |
58 | //解密字符串
59 | func (p *AesEncrypt) Decrypt(aesEncryptString string) (strDesc string, err error) {
60 | src, err := hex.DecodeString(aesEncryptString)
61 | //src, err := base64.StdEncoding.DecodeString(aesEncryptString)
62 | if err != nil {
63 | return
64 | }
65 | defer func() {
66 | //错误处理
67 | if e := recover(); e != nil {
68 | err = e.(error)
69 | }
70 | }()
71 | key := p.getKey()
72 | var iv = []byte(key)[:aes.BlockSize]
73 | decrypted := make([]byte, len(src))
74 | var aesBlockDecrypter cipher.Block
75 | aesBlockDecrypter, err = aes.NewCipher([]byte(key))
76 | if err != nil {
77 | return "", err
78 | }
79 | aesDecrypter := cipher.NewCFBDecrypter(aesBlockDecrypter, iv)
80 | aesDecrypter.XORKeyStream(decrypted, src)
81 | return string(decrypted), nil
82 | }
--------------------------------------------------------------------------------
/invest/service/request.go:
--------------------------------------------------------------------------------
1 | package service
2 |
3 | import (
4 | "github.com/astaxie/beego/logs"
5 | "game/invest/tools"
6 | "game/api/thrift/gen-go/rpc"
7 | "context"
8 | )
9 |
10 | func wsRequest(data map[string]interface{}, client *Client) {
11 | defer func() {
12 | if r:= recover(); r != nil {
13 | logs.Error("GetUserInfo panic:%v ",r)
14 | }
15 | }()
16 | if req, ok := data["act"]; ok {
17 | if act, ok := req.(string); ok {
18 | switch act {
19 | case "login_server_invest":
20 | logs.Debug("user request login")
21 | if token, ok := data["token"]; ok {
22 | if tokenStr, ok := token.(string); ok {
23 | rpcClient, closeTransport, err := tools.GetRpcClient()
24 | if err != nil {
25 | logs.Debug("get rpc client err:%v", err)
26 | }
27 | defer closeTransport()
28 |
29 | resp, err := rpcClient.GetUserInfoByken(context.Background(), tokenStr)
30 | if err != nil || resp.Code != rpc.ErrorCode_Success {
31 | logs.Debug("check user token [%v] failed err:%v, resp:%v", token, err, resp)
32 | } else {
33 | client.UserInfo.UserId = UserId(resp.UserObj.UserId)
34 | client.UserInfo.Nickname = resp.UserObj.NickName
35 | client.UserInfo.Icon = resp.UserObj.AvatarAuto
36 | client.UserInfo.Gold = int(resp.UserObj.Gold)
37 | client.Status = clientStatusGuest
38 | HubMgr.LoginChan <- client
39 | }
40 | }
41 | }
42 | case "praise_invest":
43 | if req, ok := data["num"]; ok {
44 | logs.Debug("receive num %v invalid", req)
45 | if numFloat, ok := req.(float64); ok {
46 | logs.Debug("receive str num %v invalid", req)
47 | num := int(numFloat)
48 | client.Room.Lock.Lock()
49 | defer client.Room.Lock.Unlock()
50 | for _, praiseItem := range client.Room.PraiseInfo {
51 | if praiseItem.UserId == client.UserInfo.UserId {
52 | praiseItem.Num = praiseItem.Num + num
53 | logs.Debug("room praise %v", client.Room.PraiseInfo)
54 | return
55 | }
56 | }
57 | client.Room.PraiseInfo = append(client.Room.PraiseInfo, &UserPraise{
58 | UserId: client.UserInfo.UserId,
59 | Num: num,
60 | })
61 | logs.Debug("room praise %v", client.Room.PraiseInfo)
62 | }
63 | }
64 | }
65 | }
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/invest/logic/invest/calculate.go:
--------------------------------------------------------------------------------
1 | package invest
2 |
3 | import (
4 | "math/rand"
5 | "game/invest/common"
6 | "github.com/astaxie/beego/logs"
7 | "time"
8 | )
9 |
10 | func getResult() (resultInvestConf *common.InvestConf,needGold int) {
11 | //gameInfo.Lock.Lock()
12 | //defer gameInfo.Lock.Unlock()
13 | rand.Seed(time.Now().UnixNano())
14 | randInt := rand.Intn(common.TotalWeight)
15 | var weightAdd int
16 | for _,investConf := range common.InvestConfArr{
17 | weightAdd = weightAdd + investConf.Weight
18 | if investConf.Weight == 0 {
19 | continue
20 | }
21 | if randInt <= weightAdd {
22 | resultInvestConf = investConf
23 | break
24 | }
25 | }
26 | winPositionArr := resultInvestConf.GetParents()
27 | //logs.Debug("total stake map:%v",gameInfo.StakeMap)
28 | for _,investConf := range winPositionArr{
29 | stakeGold,ok := gameInfo.StakeMap[investConf.Id]
30 | if !ok {
31 | //logs.Error("user total stake in [%d] is nil",investConf.Id)
32 | continue
33 | }
34 | needGold = needGold + int(float32(stakeGold) * investConf.Rate)
35 | }
36 | if needGold <= gameInfo.Pool{
37 | return
38 | }
39 | logs.Debug("gold in pool not enough ,pool gold %d ;need: %d",gameInfo.Pool,needGold)
40 |
41 | var legalResultMap = make(map[*common.InvestConf]int)
42 | needMinGold := needGold
43 | for _,investConf := range common.InvestConfArr{
44 | if investConf.Weight != 0 {
45 | winPositionArr := investConf.GetParents()
46 | itemNeedGold := 0
47 | for _,itemInvestConf := range winPositionArr{
48 | stakeGold,ok := gameInfo.StakeMap[itemInvestConf.Id]
49 | if !ok {
50 | //logs.Debug("user total stake in [%d] is nil",investConf.Id)
51 | continue
52 | }
53 | itemNeedGold = itemNeedGold + int(float32(stakeGold) * investConf.Rate)
54 | }
55 | if itemNeedGold <= gameInfo.Pool{
56 | needGold = itemNeedGold
57 | resultInvestConf = investConf
58 | if investConf.Id != 19 {
59 | legalResultMap[investConf] = itemNeedGold
60 | }
61 | //return
62 | }
63 | if needMinGold > itemNeedGold {
64 | needMinGold = itemNeedGold
65 | resultInvestConf = investConf
66 | }
67 | }
68 | }
69 | if len(legalResultMap) > 0 { //合法结果不止一个时,随机取一个
70 | for resultInvestConf,needMinGold = range legalResultMap{
71 | break
72 | }
73 | }
74 | return
75 | }
76 |
77 |
--------------------------------------------------------------------------------
/game.sql:
--------------------------------------------------------------------------------
1 | /*
2 | Navicat Premium Data Transfer
3 |
4 | Source Server : baidu
5 | Source Server Type : MySQL
6 | Source Server Version : 50722
7 | Source Host : 182.61.24.31:3306
8 | Source Schema : game
9 |
10 | Target Server Type : MySQL
11 | Target Server Version : 50722
12 | File Encoding : 65001
13 |
14 | Date: 23/09/2018 17:49:22
15 | */
16 |
17 | SET NAMES utf8mb4;
18 | SET FOREIGN_KEY_CHECKS = 0;
19 |
20 | -- ----------------------------
21 | -- Table structure for game_invest_base
22 | -- ----------------------------
23 | DROP TABLE IF EXISTS `game_invest_base`;
24 | CREATE TABLE `game_invest_base` (
25 | `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
26 | `game_times_id` char(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
27 | `periods` int(11) NOT NULL,
28 | `game_pool` int(11) NOT NULL COMMENT '奖池',
29 | `stake_detail` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
30 | `game_result` int(11) NOT NULL COMMENT '结果',
31 | `start_time` datetime(0) NOT NULL,
32 | PRIMARY KEY (`id`) USING BTREE
33 | ) ENGINE = InnoDB AUTO_INCREMENT = 164 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '投资大亨押注表' ROW_FORMAT = Dynamic;
34 |
35 | -- ----------------------------
36 | -- Table structure for game_invest_user_stake
37 | -- ----------------------------
38 | DROP TABLE IF EXISTS `game_invest_user_stake`;
39 | CREATE TABLE `game_invest_user_stake` (
40 | `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
41 | `game_times_id` char(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '唯一标识',
42 | `periods` int(11) NOT NULL COMMENT '期数',
43 | `room_id` int(11) NOT NULL COMMENT '房间id',
44 | `room_type` tinyint(4) NOT NULL DEFAULT 1 COMMENT '房间类型 1 普通场 2 搞几场',
45 | `user_id` int(11) NOT NULL COMMENT '用户id',
46 | `nickname` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户昵称',
47 | `user_all_stake` int(11) NOT NULL COMMENT '本场用户总押注',
48 | `get_gold` int(11) NOT NULL COMMENT '赢得金币',
49 | `stake_detail` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '押注详情',
50 | `game_result` int(11) NOT NULL COMMENT '本场开奖',
51 | `game_pool` int(11) NOT NULL COMMENT '奖池',
52 | `last_stake_time` datetime(0) NOT NULL,
53 | PRIMARY KEY (`id`) USING BTREE
54 | ) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '投资大亨' ROW_FORMAT = Dynamic;
55 |
56 | SET FOREIGN_KEY_CHECKS = 1;
57 |
--------------------------------------------------------------------------------
/invest/controllers/invest/record_list.go:
--------------------------------------------------------------------------------
1 | package invest
2 |
3 | import (
4 | "net/http"
5 | "github.com/astaxie/beego/logs"
6 | "time"
7 | "encoding/json"
8 | "game/invest/tools"
9 | "game/invest/common"
10 | "game/api/thrift/gen-go/rpc"
11 | "context"
12 | "game/invest/service"
13 | )
14 |
15 | func RecordList(w http.ResponseWriter, r *http.Request) {
16 | defer func() {
17 | if r := recover(); r != nil {
18 | logs.Error("RewardList panic:%v ", r)
19 | }
20 | }()
21 | //logs.Debug("new request url:[%s]",r.URL)
22 | ret := make(map[string]interface{})
23 | ret["time"] = time.Now().Format("2006-01-02 15:04:05")
24 | defer func() {
25 | data, err := json.Marshal(ret)
26 | if err != nil {
27 | logs.Error("json marsha1 failed err:%v", err)
28 | return
29 | }
30 | w.Header().Set("Access-Control-Allow-Origin", "*")
31 | w.Write(data)
32 | }()
33 |
34 | token := r.FormValue("token")
35 | if len(token) == 0 {
36 | token = r.PostFormValue("token")
37 | }
38 | rpcClient, closeTransport, err := tools.GetRpcClient()
39 | if err != nil {
40 | logs.Debug("get rpc client err:%v", err)
41 | ret["code"] = common.ErrorRpcServerError
42 | return
43 | }
44 | defer closeTransport()
45 |
46 | resp, err := rpcClient.GetUserInfoByken(context.Background(), token)
47 | //logs.Debug("user info %v",resp)
48 | if err != nil || resp.Code != rpc.ErrorCode_Success {
49 | logs.Debug("check user token [%v] failed err:%v, resp:%v", token, err, resp)
50 | ret["code"] = common.ErrorAuthFailed
51 | } else {
52 | ret["code"] = int(resp.Code)
53 |
54 | var stakeList []common.InvestUserStake
55 |
56 | err = service.GameConf.MysqlConf.Pool.Select(&stakeList, "select * from game_invest_user_stake where user_id=?", resp.UserObj.UserId)
57 | if err != nil {
58 | logs.Error("select user [%d] stake err:%v", resp.UserObj.UserId, err)
59 | }
60 | userStakeList := []map[string]interface{}{}
61 | for _, stakeItem := range stakeList {
62 | userStakeList = append(userStakeList, map[string]interface{}{
63 | "record_id": stakeItem.Periods,
64 | "get_gold": stakeItem.WinGold,
65 | "game_times_id": stakeItem.GameTimesId,
66 | "stake_time": stakeItem.StakeTime,
67 | "stake_gold": stakeItem.UserAllStake,
68 | })
69 | }
70 | identityObj := map[string]interface{}{
71 | "userId": resp.UserObj.UserId,
72 | "nickName": resp.UserObj.NickName,
73 | "avatarAuto": resp.UserObj.AvatarAuto,
74 | "sex": 1,
75 | "gold": resp.UserObj.Gold,
76 | "goldenBean": resp.UserObj.Gold,
77 | "diamond": 100000,
78 | "level": 12,
79 | "vipLevel": 1,
80 | }
81 | ret["result"] = map[string]interface{}{
82 | "identity_obj": identityObj,
83 | "record_list": userStakeList,
84 | }
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/back/main/config.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "github.com/astaxie/beego"
5 | "github.com/astaxie/beego/logs"
6 | "fmt"
7 | "game/invest/common"
8 | )
9 |
10 | var (
11 | backConf = &common.GameConf{}
12 | )
13 |
14 | func initConf() (err error) {
15 | //todo redis相关配置
16 | backConf.RedisConf.RedisAddr = beego.AppConfig.String("redis_addr")
17 | if len(backConf.RedisConf.RedisAddr) == 0 {
18 | err = fmt.Errorf("init config failed, redis_addr [%s]", backConf.RedisConf.RedisAddr)
19 | return
20 | }
21 | backConf.RedisConf.RedisMaxIdle,err = beego.AppConfig.Int("redis_max_idle")
22 | if err != nil {
23 | logs.Error("init config failed,read redis_max_idle err :%v", err)
24 | return
25 | }
26 | backConf.RedisConf.RedisMaxActive, err = beego.AppConfig.Int("redis_max_active")
27 | if err != nil {
28 | logs.Error("init config failed,read redis_max_active err :%v", err)
29 | return
30 | }
31 | backConf.RedisConf.RedisIdleTimeout, err = beego.AppConfig.Int("redis_idle_timeout")
32 | if err != nil {
33 | logs.Error("init config failed,read redis_idle_timeout err :%v", err)
34 | return
35 | }
36 | backConf.RedisKey.RedisKeyUserStake = beego.AppConfig.String("redis_key_user_stake_msg")
37 | if len(backConf.RedisKey.RedisKeyUserStake) == 0 {
38 | err = fmt.Errorf("init config failed, redis_key_user_stake_msg [%s]", backConf.RedisKey.RedisKeyUserStake)
39 | return
40 | }
41 | backConf.RedisKey.RedisKeyInvestBase = beego.AppConfig.String("redis_key_invest_base")
42 | if len(backConf.RedisKey.RedisKeyInvestBase) == 0 {
43 | err = fmt.Errorf("init config failed, redis_key_invest_base [%s]", backConf.RedisKey.RedisKeyInvestBase)
44 | return
45 | }
46 | //todo mysql相关配置
47 | backConf.MysqlConf.MysqlAddr = beego.AppConfig.String("mysql_addr")
48 | if len(backConf.MysqlConf.MysqlAddr) == 0 {
49 | err = fmt.Errorf("init config failed, mysql_addr [%s]", backConf.MysqlConf.MysqlAddr)
50 | return
51 | }
52 | backConf.MysqlConf.MysqlUser = beego.AppConfig.String("mysql_user")
53 | if len(backConf.MysqlConf.MysqlUser) == 0 {
54 | err = fmt.Errorf("init config failed, mysql_user [%s]", backConf.MysqlConf.MysqlUser)
55 | return
56 | }
57 | backConf.MysqlConf.MysqlPassword = beego.AppConfig.String("mysql_password")
58 | if len(backConf.MysqlConf.MysqlPassword) == 0 {
59 | err = fmt.Errorf("init config failed, mysql_password [%s]", backConf.MysqlConf.MysqlPassword)
60 | return
61 | }
62 | backConf.MysqlConf.MysqlDatabase = beego.AppConfig.String("mysql_db")
63 | if len(backConf.MysqlConf.MysqlDatabase) == 0 {
64 | err = fmt.Errorf("init config failed, mysql_password [%s]", backConf.MysqlConf.MysqlDatabase)
65 | return
66 | }
67 | //todo 日志配置
68 | backConf.LogPath = beego.AppConfig.String("log_path")
69 | backConf.LogLevel = beego.AppConfig.String("log_level")
70 |
71 | return
72 | }
73 |
--------------------------------------------------------------------------------
/back/main/init.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "github.com/astaxie/beego/logs"
5 | "github.com/garyburd/redigo/redis"
6 | "time"
7 | etcd_client "github.com/coreos/etcd/clientv3"
8 | "fmt"
9 | "encoding/json"
10 | "github.com/jmoiron/sqlx"
11 | "game/back/service"
12 | _ "github.com/go-sql-driver/mysql"
13 | )
14 |
15 | func initMysql() (err error) {
16 | conf := backConf.MysqlConf
17 | dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s",conf.MysqlUser,conf.MysqlPassword,conf.MysqlAddr,conf.MysqlDatabase)
18 | logs.Debug(dsn)
19 | database, err := sqlx.Open("mysql", dsn)
20 | if err != nil {
21 | return
22 | }
23 |
24 | backConf.MysqlConf.Pool = database
25 | return
26 | }
27 |
28 | func initRedis() (err error) {
29 | backConf.RedisConf.RedisPool = &redis.Pool{
30 | MaxIdle: backConf.RedisConf.RedisMaxIdle,
31 | MaxActive:backConf.RedisConf.RedisMaxActive,
32 | IdleTimeout:time.Duration(backConf.RedisConf.RedisIdleTimeout) * time.Second,
33 | Dial: func() (redis.Conn ,error) {
34 | return redis.Dial("tcp",backConf.RedisConf.RedisAddr)
35 | },
36 | }
37 | conn := backConf.RedisConf.RedisPool.Get()
38 | defer conn.Close()
39 | _,err = conn.Do("ping")
40 | if err != nil {
41 | logs.Error("ping redis failed,err:%v",err)
42 | return
43 | }
44 | return
45 | }
46 |
47 | func initEtcd () (err error) {
48 | cli,err := etcd_client.New(etcd_client.Config{
49 | Endpoints:[]string{backConf.EtcdConf.EtcdAddr},
50 | DialTimeout:time.Duration(backConf.EtcdConf.Timeout) * time.Second,
51 | })
52 | if err != nil {
53 | logs.Error("connect Etcd failed,err :",err)
54 | return
55 | }
56 | backConf.EtcdConf.EtcdClient = cli
57 | return
58 | }
59 |
60 | func converLogLevel(logLevel string) int {
61 | switch logLevel {
62 | case "debug":
63 | return logs.LevelDebug
64 | case "warn":
65 | return logs.LevelWarn
66 | case "info":
67 | return logs.LevelInfo
68 | case "trace":
69 | return logs.LevelTrace
70 | }
71 | return logs.LevelDebug
72 | }
73 | func initLogger() (err error) {
74 | config := make(map[string]interface{})
75 | config["filename"] = backConf.LogPath
76 | config["level"] = converLogLevel(backConf.LogLevel)
77 |
78 | configStr,err := json.Marshal(config)
79 | if err != nil {
80 | fmt.Println("marsha1 faild,err",err)
81 | return
82 | }
83 | logs.SetLogger(logs.AdapterFile,string(configStr))
84 | return
85 | }
86 |
87 |
88 | func initSec() (err error) {
89 | err = initLogger()
90 | if err != nil {
91 | logs.Error("init logger failed,err:%v",err)
92 | return
93 | }
94 | err = initRedis()
95 | if err != nil {
96 | logs.Error("init redis failed,err :%v",err)
97 | return
98 | }
99 | err = initMysql()
100 | if err != nil {
101 | logs.Error("init mysql failed,err :%v",err)
102 | return
103 | }
104 | /*err = initEtcd()
105 | if err != nil {
106 | logs.Error("init etcd failed,err:%v",err)
107 | return
108 | }*/
109 | service.Run(backConf)
110 | logs.Info("init sec succ")
111 | return
112 | }
113 |
114 |
--------------------------------------------------------------------------------
/invest/main/init.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "github.com/astaxie/beego/logs"
5 | "github.com/garyburd/redigo/redis"
6 | "time"
7 | etcd_client "github.com/coreos/etcd/clientv3"
8 | "fmt"
9 | "encoding/json"
10 | "game/invest/service"
11 | "github.com/jmoiron/sqlx"
12 | _ "github.com/go-sql-driver/mysql"
13 | )
14 |
15 | func initRedis() (err error) {
16 | gameConf.RedisConf.RedisPool = &redis.Pool{
17 | MaxIdle: gameConf.RedisConf.RedisMaxIdle,
18 | MaxActive:gameConf.RedisConf.RedisMaxActive,
19 | IdleTimeout:time.Duration(gameConf.RedisConf.RedisIdleTimeout) * time.Second,
20 | Dial: func() (redis.Conn ,error) {
21 | return redis.Dial("tcp",gameConf.RedisConf.RedisAddr)
22 | },
23 | }
24 | conn := gameConf.RedisConf.RedisPool.Get()
25 | defer conn.Close()
26 | _,err = conn.Do("ping")
27 | if err != nil {
28 | logs.Error("ping redis failed,err:%v",err)
29 | return
30 | }
31 | return
32 | }
33 |
34 | func initEtcd () (err error) {
35 | cli,err := etcd_client.New(etcd_client.Config{
36 | Endpoints:[]string{gameConf.EtcdConf.EtcdAddr},
37 | DialTimeout:time.Duration(gameConf.EtcdConf.Timeout) * time.Second,
38 | })
39 | if err != nil {
40 | logs.Error("connect Etcd failed,err :",err)
41 | return
42 | }
43 | gameConf.EtcdConf.EtcdClient = cli
44 | return
45 | }
46 |
47 | func converLogLevel(logLevel string) int {
48 | switch logLevel {
49 | case "debug":
50 | return logs.LevelDebug
51 | case "warn":
52 | return logs.LevelWarn
53 | case "info":
54 | return logs.LevelInfo
55 | case "trace":
56 | return logs.LevelTrace
57 | }
58 | return logs.LevelDebug
59 | }
60 | func initLogger() (err error) {
61 | config := make(map[string]interface{})
62 | config["filename"] = gameConf.LogPath
63 | config["level"] = converLogLevel(gameConf.LogLevel)
64 |
65 | configStr,err := json.Marshal(config)
66 | if err != nil {
67 | fmt.Println("marsha1 faild,err",err)
68 | return
69 | }
70 | logs.SetLogger(logs.AdapterFile,string(configStr))
71 | return
72 | }
73 |
74 | func initMysql() (err error) {
75 | conf := gameConf.MysqlConf
76 | dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s",conf.MysqlUser,conf.MysqlPassword,conf.MysqlAddr,conf.MysqlDatabase)
77 | logs.Debug(dsn)
78 | database, err := sqlx.Open("mysql", dsn)
79 | if err != nil {
80 | return
81 | }
82 |
83 | gameConf.MysqlConf.Pool = database
84 | return
85 | }
86 |
87 | func initSec() (err error) {
88 | err = initLogger()
89 | if err != nil {
90 | logs.Error("init logger failed,err:%v",err)
91 | return
92 | }
93 | err = initRedis()
94 | if err != nil {
95 | logs.Error("init redis failed,err :%v",err)
96 | return
97 | }
98 | /*err = initEtcd()
99 | if err != nil {
100 | logs.Error("init etcd failed,err:%v",err)
101 | return
102 | }*/
103 | err = initMysql()
104 | if err != nil {
105 | logs.Error("init mysql failed,err :%v",err)
106 | return
107 | }
108 | service.InitService(gameConf)
109 | logs.Info("init sec succ")
110 | return
111 | }
112 |
113 |
--------------------------------------------------------------------------------
/back/service/main.go:
--------------------------------------------------------------------------------
1 | package service
2 |
3 | import (
4 | "game/invest/common"
5 | "sync"
6 | "github.com/garyburd/redigo/redis"
7 | "github.com/astaxie/beego/logs"
8 | "encoding/json"
9 | "time"
10 | )
11 |
12 | var (
13 | backConf *common.GameConf
14 | wg sync.WaitGroup
15 | )
16 | func Run(conf *common.GameConf) {
17 | backConf = conf
18 | wg.Add(1)
19 | go InvestUserStake()
20 | wg.Add(1)
21 | go InvestBase()
22 | wg.Wait()
23 | }
24 |
25 | func InvestUserStake() {
26 | var conn redis.Conn
27 | conn = backConf.RedisConf.RedisPool.Get()
28 | for {
29 | resp,err := redis.String(conn.Do("RPOP",backConf.RedisKey.RedisKeyUserStake))
30 | if err != nil {
31 | time.Sleep(time.Second)
32 | logs.Error("get invest user stake message failed ,rpop [%v] err:%v",backConf.RedisKey.RedisKeyUserStake,err)
33 | continue
34 | }
35 | investUserStake := &common.InvestUserStake{}
36 | err = json.Unmarshal([]byte(resp),investUserStake)
37 | if err != nil {
38 | logs.Error("unmarsha1 invest user stake message [%v] failed err:%v",resp,err)
39 | continue
40 | }
41 | _,err = backConf.MysqlConf.Pool.Exec(`insert into game_invest_user_stake(
42 | game_times_id,periods,room_id,room_type,user_id,nickname,user_all_stake,get_gold,stake_detail,game_result,game_pool,last_stake_time)
43 | values(?,?,?,?,?,?,?,?,?,?,?,?) `,investUserStake.GameTimesId,
44 | investUserStake.Periods,
45 | investUserStake.RoomId,
46 | investUserStake.RoomType,
47 | investUserStake.UserId,
48 | investUserStake.Nickname,
49 | investUserStake.UserAllStake,
50 | investUserStake.WinGold,
51 | investUserStake.StakeDetail,
52 | investUserStake.GameResult,
53 | investUserStake.Pool,
54 | investUserStake.StakeTime,
55 | )
56 | if err != nil {
57 | logs.Error("insert user stake [%v],err :%v",investUserStake,err)
58 | continue
59 | }
60 | }
61 | conn.Close()
62 | wg.Done()
63 | }
64 | func InvestBase() {
65 | var conn redis.Conn
66 | conn = backConf.RedisConf.RedisPool.Get()
67 | for {
68 | resp,err := redis.String(conn.Do("RPOP",backConf.RedisKey.RedisKeyInvestBase))
69 | if err != nil {
70 | //logs.Debug("%T",backConf.RedisKey.RedisKeyInvestBase)
71 | time.Sleep(time.Second)
72 | logs.Error("get invest base failed ,rpop [%v] resp[%v] err:%v",backConf.RedisKey.RedisKeyInvestBase,resp,err)
73 | continue
74 | }
75 | investBase := &common.InvestBase{}
76 | err = json.Unmarshal([]byte(resp),investBase)
77 | if err != nil {
78 | logs.Error("unmarsha1 invest user stake message [%v] failed err:%v",resp,err)
79 | continue
80 | }
81 | _,err = backConf.MysqlConf.Pool.Exec(`insert into game_invest_base(
82 | game_times_id,periods,game_pool,stake_detail,game_result,start_time)
83 | values(?,?,?,?,?,?) `,investBase.GameTimesId,
84 | investBase.Periods,
85 | investBase.Pool,
86 | investBase.StakeDetail,
87 | investBase.GameResult,
88 | investBase.StartTime,
89 | )
90 | if err != nil {
91 | logs.Error("insert invest base [%v],err :%v",investBase,err)
92 | continue
93 | }
94 | }
95 | conn.Close()
96 | wg.Done()
97 | }
--------------------------------------------------------------------------------
/invest/service/client.go:
--------------------------------------------------------------------------------
1 | package service
2 |
3 | import (
4 | "bytes"
5 | "net/http"
6 | "time"
7 | "github.com/gorilla/websocket"
8 | "github.com/astaxie/beego/logs"
9 | "encoding/json"
10 | )
11 |
12 | const (
13 | writeWait = 1 * time.Second
14 | pongWait = 60 * time.Second
15 | pingPeriod = (pongWait * 9) / 10
16 | maxMessageSize = 512
17 |
18 | clientStatusGuest = 0
19 | clientStatusLogin = 1
20 | )
21 |
22 | var (
23 | newline = []byte{'\n'}
24 | space = []byte{' '}
25 | )
26 |
27 | var upgrader = websocket.Upgrader{
28 | ReadBufferSize: 1024,
29 | WriteBufferSize: 1024,
30 | CheckOrigin: func(r *http.Request) bool { return true }, //不验证origin
31 | }
32 |
33 | type UserInfo struct {
34 | UserId UserId `json:"user_id"`
35 | Nickname string `json:"nickname"`
36 | Icon string `json:"icon"`
37 | Gold int `json:"gold"`
38 | }
39 |
40 | type Client struct {
41 | Hub *Hub
42 | conn *websocket.Conn
43 | UserInfo *UserInfo
44 | Status int
45 | Room *Room
46 | }
47 |
48 | func (c *Client) sendMsg(msg []byte) {
49 | c.conn.SetWriteDeadline(time.Now().Add(writeWait))
50 | w, err := c.conn.NextWriter(websocket.TextMessage)
51 | if err != nil {
52 | c.Room.Lock.Lock()
53 | if _,ok := c.Room.RoomClients[c.UserInfo.UserId];ok {
54 | delete(c.Room.RoomClients,c.UserInfo.UserId)
55 | }
56 | c.Room.Lock.Unlock()
57 |
58 | c.conn.Close()
59 | c.Room.LoginOutChan <- c
60 | }
61 | w.Write(msg)
62 | if err := w.Close(); err != nil {
63 | c.Room.Lock.Lock()
64 | if _,ok := c.Room.RoomClients[c.UserInfo.UserId];ok {
65 | delete(c.Room.RoomClients,c.UserInfo.UserId)
66 | }
67 | c.Room.Lock.Unlock()
68 |
69 | c.conn.Close()
70 | c.Room.LoginOutChan <- c
71 | }
72 | }
73 |
74 | func (c *Client) readPump() {
75 | defer func() {
76 | if c.Status == clientStatusLogin {
77 | c.Room.Lock.Lock()
78 | if _,ok := c.Room.RoomClients[c.UserInfo.UserId];ok {
79 | delete(c.Room.RoomClients,c.UserInfo.UserId)
80 | }
81 | c.Room.Lock.Unlock()
82 | c.Room.LoginOutChan <- c
83 | }
84 | c.conn.Close()
85 | }()
86 | c.conn.SetReadLimit(maxMessageSize)
87 | c.conn.SetReadDeadline(time.Now().Add(pongWait))
88 | c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
89 | for {
90 | _, message, err := c.conn.ReadMessage()
91 | if err != nil {
92 | if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
93 | logs.Error("websocket user_id[%d] unexpected close error: %v", c.UserInfo.UserId, err)
94 | }
95 | return
96 | }
97 | message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))
98 | logs.Debug("receive message from client:%s", message)
99 | data := make(map[string]interface{})
100 | err = json.Unmarshal(message, &data)
101 | if err != nil {
102 | logs.Error("message unmarsha1 err, user_id[%d] err:%v", c.UserInfo.UserId, err)
103 | } else {
104 | wsRequest(data, c)
105 | }
106 | }
107 | }
108 |
109 | func ServeWs(w http.ResponseWriter, r *http.Request) {
110 | conn, err := upgrader.Upgrade(w, r, nil)
111 | if err != nil {
112 | logs.Error("upgrader err:%v", err)
113 | return
114 | }
115 | client := &Client{Hub: HubMgr, conn: conn, UserInfo: &UserInfo{}}
116 |
117 | go client.readPump()
118 | }
119 |
--------------------------------------------------------------------------------
/invest/logic/invest/record.go:
--------------------------------------------------------------------------------
1 | package invest
2 |
3 | import (
4 | "game/invest/common"
5 | "time"
6 | )
7 |
8 | func record() {
9 | for {
10 | date := time.Now().Format("2006-01-02")
11 | select {
12 | case gameResult := <-common.GameRecord.ResultChan:
13 | common.GameRecord.Lock.Lock()
14 | for i := 0; i < len(common.GameRecord.LasTTenTimesRank); i++ {
15 | if i == len(common.GameRecord.LasTTenTimesRank)-1 {
16 | common.GameRecord.LasTTenTimesRank[len(common.GameRecord.LasTTenTimesRank)-1] = &common.GameRank{
17 | Periods: gameManage.TimesId,
18 | GameResult: gameResult,
19 | }
20 | } else if common.GameRecord.LasTTenTimesRank[i] == nil {
21 | gameManage.Lock.RLock()
22 | common.GameRecord.LasTTenTimesRank[i] = &common.GameRank{
23 | Periods: gameManage.TimesId,
24 | GameResult: gameResult,
25 | }
26 | gameManage.Lock.RUnlock()
27 | break
28 | } else if common.GameRecord.LasTTenTimesRank[i+1] == nil {
29 | gameManage.Lock.RLock()
30 | common.GameRecord.LasTTenTimesRank[i+1] = &common.GameRank{
31 | Periods: gameManage.TimesId,
32 | GameResult: gameResult,
33 | }
34 | gameManage.Lock.RUnlock()
35 | break
36 | } else {
37 | common.GameRecord.LasTTenTimesRank[i] = common.GameRecord.LasTTenTimesRank[i+1]
38 | }
39 | }
40 |
41 | lostPositionArr := make([]*common.InvestConf, 0)
42 |
43 | common.GameRecord.UnfortunatelyRecord = &common.UnfortunatelyPosition{}
44 | for _, investConf := range common.InvestConfArr {
45 | isWinPosition := false
46 | for _, winPosition := range gameResult.WinPosition {
47 | if investConf.Id == winPosition {
48 | isWinPosition = true
49 | break
50 | }
51 | }
52 | if !isWinPosition {
53 | //连续赢的记录清零
54 | lostPositionArr = append(lostPositionArr, investConf)
55 | common.GameRecord.ContinuedWinRecord[investConf] = 0
56 |
57 | //连续输的记录 +1
58 | if _, ok := common.GameRecord.LastTimeWinRecord[investConf.Id]; ok {
59 | common.GameRecord.LastTimeWinRecord[investConf.Id]++
60 | } else {
61 | common.GameRecord.LastTimeWinRecord[investConf.Id] = 1
62 | }
63 |
64 | //记录最不幸的位置
65 | if common.GameRecord.UnfortunatelyRecord.Count < common.GameRecord.LastTimeWinRecord[investConf.Id] {
66 | common.GameRecord.UnfortunatelyRecord.Count = common.GameRecord.LastTimeWinRecord[investConf.Id]
67 | common.GameRecord.UnfortunatelyRecord.Position = investConf.Id
68 | }
69 | } else {
70 | //连续赢的记录 +1
71 | if _, ok := common.GameRecord.ContinuedWinRecord[investConf]; ok {
72 | common.GameRecord.ContinuedWinRecord[investConf]++
73 | } else {
74 | common.GameRecord.ContinuedWinRecord[investConf] = 1
75 | }
76 |
77 | //连续输的记录 清零
78 | common.GameRecord.LastTimeWinRecord[investConf.Id] = 0
79 |
80 | if common.GameRecord.EverydayResultRecord.Date == date {
81 | if _, ok := common.GameRecord.EverydayResultRecord.Record[investConf]; ok {
82 | common.GameRecord.EverydayResultRecord.Record[investConf]++
83 | } else {
84 | common.GameRecord.EverydayResultRecord.Record[investConf] = 1
85 | }
86 | } else {
87 | common.GameRecord.EverydayResultRecord = &common.EveryDayRecord{
88 | Date: date,
89 | Record: map[*common.InvestConf]int{investConf: 1},
90 | }
91 | }
92 | }
93 | }
94 | common.GameRecord.Lock.Unlock()
95 | }
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/invest/service/hub.go:
--------------------------------------------------------------------------------
1 | package service
2 |
3 | import (
4 | "sync"
5 | "github.com/astaxie/beego/logs"
6 | "game/invest/common"
7 | )
8 |
9 | type RoomId int
10 | type UserId int
11 |
12 | type Hub struct {
13 | Rooms map[*Room]int //房间人数映射
14 | UserToRoom map[UserId]*Room
15 | CenterCommandChan chan *common.Message //center发送的游戏状态
16 |
17 | LoginChan chan *Client //登录房间
18 | RoomIdInr RoomId //获取自增room_id
19 | GameInfo *common.GameInfo
20 | GameManage *common.GameManage //游戏状态
21 | LoginOutMap map[UserId]*Client
22 | Lock sync.RWMutex
23 | }
24 |
25 | func NewHub() (hub *Hub, err error) {
26 | hub = &Hub{
27 | Rooms: make(map[*Room]int),
28 | UserToRoom: make(map[UserId]*Room),
29 | CenterCommandChan: make(chan *common.Message, 10),
30 | LoginChan: make(chan *Client, 1000),
31 | LoginOutMap: make(map[UserId]*Client, 1000),
32 | }
33 | return
34 | }
35 |
36 | func (h *Hub) run() {
37 | for {
38 | select {
39 | case cli := <-h.LoginChan:
40 | h.Lock.Lock()
41 | //判断是否重复登录
42 | if _,ok := h.UserToRoom[cli.UserInfo.UserId];ok {
43 | h.Lock.Unlock()
44 | continue
45 | }
46 | //判断是否重连用户
47 | if prevCli, ok := h.LoginOutMap[cli.UserInfo.UserId]; ok {
48 | room := prevCli.Room
49 | cli.Hub = HubMgr
50 | cli.Room = room
51 | cli.Status = clientStatusLogin
52 |
53 | h.UserToRoom[cli.UserInfo.UserId] = room
54 | h.Lock.Unlock()
55 | room.Lock.Lock()
56 | if previousCli, ok := room.LoginOutMap[cli.UserInfo.UserId]; ok {
57 | delete(room.LoginOutMap, cli.UserInfo.UserId)
58 | room.RoomClients[cli.UserInfo.UserId] = cli
59 | if _, ok := room.StakeInfoMap[previousCli]; ok {
60 | room.StakeInfoMap[cli] = room.StakeInfoMap[previousCli]
61 | delete(room.StakeInfoMap, previousCli)
62 | }
63 | if _, ok := room.WaitSendStakeInfoMap[previousCli]; ok {
64 | room.WaitSendStakeInfoMap[cli] = room.WaitSendStakeInfoMap[previousCli]
65 | delete(room.WaitSendStakeInfoMap, previousCli)
66 | }
67 | } else {
68 | logs.Error("user [%d] in hub,but not in room [%d]", cli.UserInfo.UserId, room.RoomId)
69 | }
70 | delete(h.LoginOutMap, cli.UserInfo.UserId)
71 | room.Lock.Unlock()
72 |
73 | h.Lock.RLock()
74 | room.UserLoginResponse(cli)
75 | h.Lock.RUnlock()
76 |
77 | continue
78 | }
79 | h.Lock.Unlock()
80 |
81 | //加入游戏
82 | h.Lock.RLock()
83 | success := false
84 | for room, count := range h.Rooms {
85 | if count < 5 {
86 |
87 | h.Lock.RUnlock() //释放读锁,方法内加写锁
88 | ok, err := room.IntoRoom(cli)
89 | h.Lock.RLock()
90 |
91 | if err != nil {
92 | logs.Error("user [%d] into room failed,err:%v", cli.UserInfo.UserId, err)
93 | continue
94 | }
95 | if ok {
96 | logs.Debug("user into room succ")
97 | success = true
98 | //todo 通知房间用户
99 | room.UserLoginResponse(cli)
100 | break
101 | }
102 | }
103 | }
104 | if !success {
105 | room := cli.NewRoom()
106 | room.UserLoginResponse(cli)
107 | }
108 | h.Lock.RUnlock()
109 | }
110 | }
111 | }
112 |
113 | func (h *Hub) broadcast() {
114 | for {
115 | select {
116 | case message := <-h.CenterCommandChan:
117 | //logs.Debug("game status %v",message.Type)
118 | for room := range h.Rooms {
119 | room.TeamRadio <- message
120 | }
121 | if message.Type == common.StatusPrepare {
122 | h.Lock.Lock()
123 | for _, cli := range h.LoginOutMap {
124 | if _, ok := h.UserToRoom[cli.UserInfo.UserId]; ok {
125 | delete(h.UserToRoom, cli.UserInfo.UserId)
126 | }
127 | }
128 | h.LoginOutMap = make(map[UserId]*Client)
129 | h.Lock.Unlock()
130 | }
131 | }
132 | }
133 | }
134 |
--------------------------------------------------------------------------------
/invest/main/config.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "github.com/astaxie/beego"
5 | "github.com/astaxie/beego/logs"
6 | "fmt"
7 | "game/invest/common"
8 | )
9 |
10 | var (
11 | gameConf = &common.GameConf{}
12 | )
13 |
14 | func initConf() (err error) {
15 | gameConf.HttpPort,err = beego.AppConfig.Int("http_port")
16 | if err != nil {
17 | logs.Error("init http_port failed,err:%v",err)
18 | return
19 | }
20 | logs.Debug("read conf succ,http port %v", gameConf.HttpPort)
21 |
22 | // redis相关配置
23 | gameConf.RedisConf.RedisAddr = beego.AppConfig.String("redis_addr")
24 | if len(gameConf.RedisConf.RedisAddr) == 0 {
25 | err = fmt.Errorf("init config failed, redis_addr [%s]", gameConf.RedisConf.RedisAddr)
26 | return
27 | }
28 | gameConf.RedisConf.RedisMaxIdle,err = beego.AppConfig.Int("redis_max_idle")
29 | if err != nil {
30 | logs.Error("init config failed,read redis_max_idle err :%v", err)
31 | return
32 | }
33 | gameConf.RedisConf.RedisMaxActive, err = beego.AppConfig.Int("redis_max_active")
34 | if err != nil {
35 | logs.Error("init config failed,read redis_max_active err :%v", err)
36 | return
37 | }
38 | gameConf.RedisConf.RedisIdleTimeout, err = beego.AppConfig.Int("redis_idle_timeout")
39 | if err != nil {
40 | logs.Error("init config failed,read redis_idle_timeout err :%v", err)
41 | return
42 | }
43 | gameConf.RedisKey.RedisKeyUserStake = beego.AppConfig.String("redis_key_user_stake_msg")
44 | if len(gameConf.RedisKey.RedisKeyUserStake) == 0 {
45 | err = fmt.Errorf("init config failed, redis_key_user_stake_msg [%s]", gameConf.RedisKey.RedisKeyUserStake)
46 | return
47 | }
48 | gameConf.RedisKey.RedisKeyInvestBase = beego.AppConfig.String("redis_key_invest_base")
49 | if len(gameConf.RedisKey.RedisKeyInvestBase) == 0 {
50 | err = fmt.Errorf("init config failed, redis_key_invest_base [%s]", gameConf.RedisKey.RedisKeyInvestBase)
51 | return
52 | }
53 | // mysql相关配置
54 | gameConf.MysqlConf.MysqlAddr = beego.AppConfig.String("mysql_addr")
55 | if len(gameConf.MysqlConf.MysqlAddr) == 0 {
56 | err = fmt.Errorf("init config failed, mysql_addr [%s]", gameConf.MysqlConf.MysqlAddr)
57 | return
58 | }
59 | gameConf.MysqlConf.MysqlUser = beego.AppConfig.String("mysql_user")
60 | if len(gameConf.MysqlConf.MysqlUser) == 0 {
61 | err = fmt.Errorf("init config failed, mysql_user [%s]", gameConf.MysqlConf.MysqlUser)
62 | return
63 | }
64 | gameConf.MysqlConf.MysqlPassword = beego.AppConfig.String("mysql_password")
65 | if len(gameConf.MysqlConf.MysqlPassword) == 0 {
66 | err = fmt.Errorf("init config failed, mysql_password [%s]", gameConf.MysqlConf.MysqlPassword)
67 | return
68 | }
69 | gameConf.MysqlConf.MysqlDatabase = beego.AppConfig.String("mysql_db")
70 | if len(gameConf.MysqlConf.MysqlDatabase) == 0 {
71 | err = fmt.Errorf("init config failed, mysql_password [%s]", gameConf.MysqlConf.MysqlDatabase)
72 | return
73 | }
74 |
75 | // etcd相关配置
76 | gameConf.EtcdConf.EtcdAddr = beego.AppConfig.String("etcd_addr")
77 | if len(gameConf.EtcdConf.EtcdAddr) == 0 {
78 | err = fmt.Errorf("init config failed, etcd_addr [%s]", gameConf.EtcdConf.EtcdAddr)
79 | return
80 | }
81 | gameConf.EtcdConf.Timeout, err = beego.AppConfig.Int("etcd_timeout")
82 | if err != nil {
83 | err = fmt.Errorf("init config failed,read etcd_timeout err :%v", err)
84 | return
85 | }
86 |
87 | // 密钥
88 | gameConf.AppSecret = beego.AppConfig.String("app_secret")
89 | if len(gameConf.AppSecret) == 0 {
90 | err = fmt.Errorf("init config failed, app_secret [%s]", gameConf.AppSecret)
91 | return
92 | }
93 |
94 | // 日志配置
95 | gameConf.LogPath = beego.AppConfig.String("log_path")
96 | gameConf.LogLevel = beego.AppConfig.String("log_level")
97 |
98 | //todo 配置到etcd
99 | gameConf.PumpingRate,err = beego.AppConfig.Int("pumping_rate")
100 | if err != nil {
101 | err = fmt.Errorf("init config failed,read pumping_rate err :%v", err)
102 | return
103 | }
104 | if gameConf.PumpingRate < 0 || gameConf.PumpingRate > 10 {
105 | err = fmt.Errorf("init config failed,config pumping_rate [%d] out of range ", gameConf.PumpingRate)
106 | return
107 | }
108 | return
109 | }
110 |
--------------------------------------------------------------------------------
/invest/logic/invest/main.go:
--------------------------------------------------------------------------------
1 | package invest
2 |
3 | import (
4 | "time"
5 | "game/invest/tools"
6 | "game/invest/common"
7 | "github.com/astaxie/beego/logs"
8 | "encoding/json"
9 | )
10 |
11 | var (
12 | gameConf *common.GameConf
13 | gameManage = &common.GameManage{
14 | Timer: -1,
15 | }
16 | sendInterval = 1 //发送押注间隔,可调节,作为服务降级
17 | CenterCommandChan chan *common.Message
18 | gameInfo *common.GameInfo
19 | )
20 |
21 | func InitInvest(ch chan *common.Message, conf *common.GameConf) (GameInfo *common.GameInfo, GameManage *common.GameManage) {
22 | GameManage = gameManage
23 | CenterCommandChan = ch
24 | gameConf = conf
25 | GameInfo = &common.GameInfo{
26 | StakeMap: make(map[int]int),
27 | GameResult: common.InvestConfArr[0],
28 | Pool: 10000, //初始奖池
29 | }
30 | gameInfo = GameInfo
31 | return
32 | }
33 |
34 | //启动游戏
35 | func RunLogic() {
36 | go record()
37 | go func() {
38 | t := time.NewTicker(time.Second)
39 | defer t.Stop()
40 | for {
41 | select {
42 | case <-t.C:
43 | tick()
44 | }
45 | }
46 | }()
47 | }
48 |
49 | func tick() {
50 | gameManage.Lock.Lock()
51 | defer gameManage.Lock.Unlock()
52 | gameManage.Timer++
53 | gameManage.StakeCountdown = gameManage.StakeCountdown - 1
54 | gameStatus, ok := common.Timer[gameManage.Timer]
55 | if ok {
56 | gameManage.GameStatus = gameStatus
57 | switch gameStatus {
58 | case common.StatusPrepare:
59 | gameManage.Periods++
60 | gameManage.Timer = 0
61 | gameManage.SendTime = 0
62 | gameManage.TimesId = tools.CreateUid()
63 |
64 | gameInfo.Lock.Lock()
65 | gameInfo.Periods = gameManage.Periods
66 | gameInfo.StakeMap = make(map[int]int)
67 | gameInfo.Lock.Unlock()
68 | case common.StatusStartStake:
69 | gameManage.StakeCountdown = 27
70 | case common.StatusEndStake:
71 | defer func() {
72 | var needGold int
73 | gameInfo.Lock.Lock()
74 | gameInfo.GameResult, needGold = getResult()
75 | common.GameRecord.ResultChan <- gameInfo.GameResult
76 | gameInfo.Pool = gameInfo.Pool - needGold
77 | gameInfo.Lock.Unlock()
78 |
79 | message := &common.Message{
80 | Type: common.StatusSendResult,
81 | Timer: gameManage.StakeCountdown,
82 | }
83 | CenterCommandChan <- message
84 |
85 | go func() {
86 | //todo 持久化消息
87 | gameInfo.Lock.RLock()
88 | //logs.Debug(" get gameInfo lock")
89 | pool := gameInfo.Pool
90 | periods := gameInfo.Periods
91 | gameResult := gameInfo.GameResult.Id
92 | stakeDetail, err := json.Marshal(gameInfo.StakeMap)
93 | if err != nil {
94 | logs.Error("json marsha1 total stake detail [%v] err:%v", gameInfo.StakeMap, err)
95 | stakeDetail = []byte{}
96 | }
97 | gameInfo.Lock.RUnlock()
98 |
99 | gameManage.Lock.RLock()
100 | gameTimesId := gameManage.TimesId
101 | gameManage.Lock.RUnlock()
102 |
103 | conn := gameConf.RedisConf.RedisPool.Get()
104 | defer conn.Close()
105 | data := common.InvestBase{
106 | GameTimesId: gameTimesId,
107 | Periods: periods,
108 | Pool: pool,
109 | GameResult: gameResult,
110 | StakeDetail: string(stakeDetail),
111 | StartTime: time.Now().Format("2006-01-02 15:04:05"),
112 | }
113 | dataStr, err := json.Marshal(data)
114 | if err != nil {
115 | logs.Error("json marsha1 invest base err:%v", err)
116 | return
117 | }
118 | _, err = conn.Do("lPush", gameConf.RedisKey.RedisKeyInvestBase, string(dataStr))
119 | //logs.Debug("lPush [%v] total user stake msg [%v]", gameConf.RedisKey.RedisKeyInvestBase, string(dataStr))
120 | if err != nil {
121 | if err != nil {
122 | logs.Error("lPush total user stake msg [%v] failed, err:%v", gameConf.RedisKey.RedisKeyInvestBase, err)
123 | }
124 | }
125 | }()
126 | }()
127 | }
128 | message := &common.Message{
129 | Type: gameStatus,
130 | Timer: gameManage.StakeCountdown,
131 | }
132 | CenterCommandChan <- message
133 | }
134 | if gameManage.GameStatus == common.StatusSendStake { //处理发送押注
135 | gameManage.SendTime++
136 | if gameManage.SendTime%sendInterval == 0 {
137 | message := &common.Message{
138 | Type: gameManage.GameStatus,
139 | Timer: gameManage.StakeCountdown,
140 | }
141 | CenterCommandChan <- message
142 | }
143 | }
144 | }
145 |
--------------------------------------------------------------------------------
/account/service/handle.go:
--------------------------------------------------------------------------------
1 | package service
2 |
3 | import (
4 | "game/api/thrift/gen-go/rpc"
5 | "github.com/garyburd/redigo/redis"
6 | "strconv"
7 | "github.com/astaxie/beego/logs"
8 | "game/account/common"
9 | "fmt"
10 | "context"
11 | "strings"
12 | )
13 |
14 | func (p *UserServer) CreateNewUser(ctx context.Context, nickName string, avatarAuto string, gold int64) (r *rpc.Result_, err error) {
15 | logs.Debug("CreateNewUser nickName: %v", nickName)
16 | r = rpc.NewResult_()
17 | conn := userServiceConf.RedisConf.RedisPool.Get()
18 | defer conn.Close()
19 | userId, err := redis.Int(conn.Do("incr", "user_id_incr"))
20 | if err != nil {
21 | logs.Error("incr err:%v", err)
22 | return
23 | }
24 | logs.Debug("new user_id:%v", userId)
25 | if err != nil {
26 | r.Code = rpc.ErrorCode_UnknowError
27 | return
28 | }
29 | userRedisKey := userServiceConf.UserRedisPrefix + strconv.Itoa(userId)
30 | conn.Do("hmset", userRedisKey, "user_id", userId, "nick_name", nickName, "avatar_auto", avatarAuto, "gold", gold)
31 | r.UserObj = rpc.NewUserInfo()
32 | r.UserObj.UserId = int64(userId)
33 | r.UserObj.NickName = nickName
34 | r.UserObj.AvatarAuto = avatarAuto
35 | r.UserObj.Gold = gold
36 | r.UserObj.Token, err = common.CreateToken(r.UserObj.UserId)
37 | return
38 | }
39 |
40 | func (p *UserServer) GetUserInfoById(ctx context.Context, userId int32) (r *rpc.Result_, err error) {
41 | r = rpc.NewResult_()
42 | r.UserObj = rpc.NewUserInfo()
43 | logs.Debug("GetUserInfoById userId: %v", userId)
44 | conn := userServiceConf.RedisConf.RedisPool.Get()
45 | defer conn.Close()
46 | if err != nil {
47 | r.Code = rpc.ErrorCode_UnknowError
48 | return
49 | }
50 |
51 | userRedisKey := userServiceConf.UserRedisPrefix + strconv.Itoa(int(userId))
52 | userExists, err := redis.Bool(conn.Do("exists", userRedisKey))
53 | if err != nil {
54 | logs.Error("check user [%d] exists err:%v", userId, err)
55 | return
56 | }
57 | if !userExists {
58 | r.Code = rpc.ErrorCode_UserIsNull
59 | return
60 | }
61 | resp, err := redis.StringMap(conn.Do("hgetall", userRedisKey))
62 | if userIdStr, ok := resp["user_id"]; ok {
63 | var userId int
64 | userId, err = strconv.Atoi(userIdStr)
65 | if err != nil {
66 | r.Code = rpc.ErrorCode_UnknowError
67 | return
68 | }
69 | r.UserObj.UserId = int64(userId)
70 | }
71 | if goldStr, ok := resp["gold"]; ok {
72 | var gold int
73 | gold, err = strconv.Atoi(goldStr)
74 | if err != nil {
75 | r.Code = rpc.ErrorCode_UnknowError
76 | return
77 | }
78 | r.UserObj.Gold = int64(gold)
79 | }
80 | if nickName, ok := resp["nick_name"]; ok {
81 | r.Code = rpc.ErrorCode_UnknowError
82 | r.UserObj.NickName = nickName
83 | }
84 | if avatarAuto, ok := resp["avatar_auto"]; ok {
85 | r.UserObj.AvatarAuto = avatarAuto
86 | }
87 | r.Code = rpc.ErrorCode_Success
88 | logs.Debug("user obj :%v",r.UserObj)
89 | return
90 | }
91 |
92 | func (p *UserServer) GetUserInfoByken(ctx context.Context, token string) (r *rpc.Result_, err error) {
93 | token = strings.Replace(token, " ", "+", -1)
94 | logs.Debug("GetUserInfoByken token %v", token)
95 | userId, err := common.CheckToken(token)
96 | if err != nil {
97 | return
98 | }
99 | r, err = p.GetUserInfoById(ctx, int32(userId))
100 | return
101 | }
102 |
103 | func (p *UserServer) ModifyGoldById(ctx context.Context, behavior string, userId int32, gold int64) (r *rpc.Result_, err error) {
104 | logs.Debug("Modify Gold [%d] By Id [%d] behavior: %v ,", gold, userId, behavior)
105 | r = rpc.NewResult_()
106 | conn := userServiceConf.RedisConf.RedisPool.Get()
107 | defer conn.Close()
108 | userRedisKey := userServiceConf.UserRedisPrefix + strconv.Itoa(int(userId))
109 | userExists, err := redis.Bool(conn.Do("exists", userRedisKey))
110 | if err != nil {
111 | logs.Error("check user [%d] exists err:%v", userId, err)
112 | return
113 | }
114 | if !userExists {
115 | r.Code = rpc.ErrorCode_UserIsNull
116 | return
117 | }
118 | leftGold, err := redis.Int(conn.Do("hincrby", userRedisKey, "gold", gold))
119 | if err != nil {
120 | r.Code = rpc.ErrorCode_UnknowError
121 | logs.Error("ModifyGoldById err:%v", err)
122 | return
123 | }
124 | if leftGold < 0 {
125 | r.Code = rpc.ErrorCode_GoldNotEnough
126 | conn.Do("hincrby", userServiceConf.UserRedisPrefix+strconv.Itoa(int(userId)), "gold", -1*gold)
127 | err = fmt.Errorf("user gold not enough")
128 | return
129 | }
130 | r, err = p.GetUserInfoById(ctx, userId)
131 | return
132 | }
133 |
134 | func (p *UserServer) ModifyGoldByToken(ctx context.Context, behavior string, token string, gold int64) (r *rpc.Result_, err error) {
135 | //logs.Debug("ModifyGoldByToken token: %v", token)
136 | r = rpc.NewResult_()
137 | userId, err := common.CheckToken(token)
138 | if err != nil {
139 | r.Code = rpc.ErrorCode_VerifyError
140 | logs.Error("check token [%s] failed", token)
141 | return
142 | }
143 | r, err = p.ModifyGoldById(ctx, behavior, int32(userId), gold)
144 | return
145 | }
146 |
--------------------------------------------------------------------------------
/invest/controllers/invest/stake.go:
--------------------------------------------------------------------------------
1 | package invest
2 |
3 | import (
4 | "net/http"
5 | "github.com/astaxie/beego/logs"
6 | "strconv"
7 | "game/invest/tools"
8 | "game/invest/service"
9 | "game/invest/common"
10 | "golang.org/x/net/context"
11 | "encoding/json"
12 | "game/api/thrift/gen-go/rpc"
13 | "time"
14 | )
15 |
16 | func Stake(w http.ResponseWriter, r *http.Request) {
17 | defer func() {
18 | if r:= recover(); r != nil {
19 | logs.Error("GetUserInfo panic:%v ",r)
20 | }
21 | }()
22 | //logs.Debug("new request url:[%s]",r.URL)
23 | ret := make(map[string]interface{})
24 | ret["time"] = time.Now().Format("2006-01-02 15:04:05")
25 | defer func() {
26 | data, err := json.Marshal(ret)
27 | if err != nil {
28 | logs.Error("json marsha1 failed err:%v", err)
29 | return
30 | }
31 | w.Header().Set("Access-Control-Allow-Origin", "*")
32 | w.Write(data)
33 | }()
34 | stakeItemIdStr := r.FormValue("stake_item_id")
35 | stakeItemId, err := strconv.Atoi(stakeItemIdStr)
36 | if err != nil {
37 | ret["code"] = common.ErrorParamInvalid
38 | logs.Error("request invest stake param stake_item_id [%s] err:", stakeItemIdStr, err)
39 | return
40 | }
41 |
42 | var positionCheck bool
43 | for _, investConf := range common.InvestConfArr {
44 | if investConf.Id == stakeItemId {
45 | positionCheck = true
46 | break
47 | }
48 | }
49 | if !positionCheck {
50 | ret["code"] = common.ErrorParamInvalid
51 | logs.Error("user [] stake in err position :%v", stakeItemId)
52 | return
53 | }
54 |
55 | stakeGoldenBeanStr := r.FormValue("stake_golden_bean")
56 | stakeGoldenBean, err := strconv.Atoi(stakeGoldenBeanStr)
57 | if err != nil || stakeGoldenBean <= 0 {
58 | ret["code"] = common.ErrorParamInvalid
59 | logs.Error("request invest stake param stakeGoldenBean [%s] err:", stakeGoldenBeanStr, err)
60 | return
61 | }
62 |
63 | token := r.FormValue("token")
64 | rpcClient, closeTransport, err := tools.GetRpcClient()
65 | if err != nil {
66 | logs.Debug("get rpc client err:%v", err)
67 | ret["code"] = common.ErrorRpcServerError
68 | }
69 | defer closeTransport()
70 |
71 | resp, err := rpcClient.GetUserInfoByken(context.Background(), token)
72 | if err != nil || resp.Code != rpc.ErrorCode_Success {
73 | ret["code"] = common.ErrorAuthFailed
74 | logs.Debug("check user token [%v] failed", token)
75 | } else {
76 | userId := resp.UserObj.UserId
77 | c, ok := service.HubMgr.UserToRoom[service.UserId(userId)]
78 | if !ok {
79 | ret["code"] = common.ErrorUnknownError
80 | logs.Error("user [%d] request invest stake ,but not in room ", userId)
81 | return
82 | }
83 | var canStakeGoldList [3]int
84 | for _, v := range common.CanStakeChipConf {
85 | if v.GoldMax == -1 && resp.UserObj.Gold >= v.GoldMin {
86 | canStakeGoldList = v.Chips
87 | } else if resp.UserObj.Gold >= v.GoldMin && resp.UserObj.Gold <= v.GoldMax {
88 | canStakeGoldList = v.Chips
89 | }
90 | }
91 | if len(canStakeGoldList) != 3 {
92 | ret["code"] = common.ErrorUnknownError
93 | return
94 | }
95 | var stakeGoldCheck bool
96 | for _, stakeGold := range canStakeGoldList {
97 | if stakeGold == stakeGoldenBean {
98 | stakeGoldCheck = true
99 | }
100 | }
101 | if !stakeGoldCheck {
102 | //不开启验证
103 | //ret["code"] = common.ErrorParamInvalid
104 | //return
105 | }
106 | if client, ok := c.RoomClients[service.UserId(userId)]; ok {
107 | if service.HubMgr.GameManage.GameStatus == common.StatusStartStake || service.HubMgr.GameManage.GameStatus == common.StatusSendStake {
108 | resp, err := rpcClient.ModifyGoldById(context.Background(), "invest_stake", int32(userId), -1*int64(stakeGoldenBean))
109 | if err != nil || resp.Code != rpc.ErrorCode_Success {
110 | ret["code"] = common.ErrorGoldNotEnough
111 | return
112 | } else {
113 | successCh := make(chan bool, 1)
114 | defer close(successCh)
115 | c.UserStakeChan <- &service.StakeInfo{
116 | Client: client,
117 | Position: stakeItemId,
118 | StakeGold: stakeGoldenBean,
119 | SuccessCh: successCh,
120 | }
121 | select {
122 | case stakeSuccess := <-successCh:
123 | if stakeSuccess {
124 | ret["code"] = common.CodeSuccess
125 | identityObj := map[string]interface{}{
126 | "userId": resp.UserObj.UserId,
127 | "nickName": resp.UserObj.NickName,
128 | "avatarAuto": resp.UserObj.AvatarAuto,
129 | "sex": 1,
130 | "gold": resp.UserObj.Gold,
131 | "goldenBean": resp.UserObj.Gold,
132 | "diamond": 100000,
133 | "level": 12,
134 | "vipLevel": 1,
135 | }
136 | ret["result"] = map[string]interface{}{
137 | "identity_obj": identityObj,
138 | }
139 | ret["msg"] = "押注成功"
140 | } else {
141 | ret["code"] = common.ErrorNotStakeTime
142 | rpcClient.ModifyGoldById(context.Background(), "invest_stake", int32(userId), int64(stakeGoldenBean))
143 | }
144 | }
145 | }
146 | }
147 | }
148 | }
149 | }
150 |
--------------------------------------------------------------------------------
/invest/controllers/invest/record_detail.go:
--------------------------------------------------------------------------------
1 | package invest
2 |
3 | import (
4 | "net/http"
5 | "github.com/astaxie/beego/logs"
6 | "time"
7 | "encoding/json"
8 | "game/invest/tools"
9 | "game/invest/common"
10 | "game/api/thrift/gen-go/rpc"
11 | "context"
12 | "game/invest/service"
13 | )
14 |
15 | func RecordDetail(w http.ResponseWriter, r *http.Request) {
16 | defer func() {
17 | if r := recover(); r != nil {
18 | logs.Error("RewardList panic:%v ", r)
19 | }
20 | }()
21 | //logs.Debug("new request url:[%s]",r.URL)
22 | ret := make(map[string]interface{})
23 | ret["time"] = time.Now().Format("2006-01-02 15:04:05")
24 | defer func() {
25 | data, err := json.Marshal(ret)
26 | if err != nil {
27 | logs.Error("json marsha1 failed err:%v", err)
28 | return
29 | }
30 | w.Header().Set("Access-Control-Allow-Origin", "*")
31 | w.Write(data)
32 | }()
33 |
34 | token := r.FormValue("token")
35 | gameTimesId := r.FormValue("game_times_id")
36 | if len(token) == 0 {
37 | token = r.PostFormValue("token")
38 | }
39 | rpcClient, closeTransport, err := tools.GetRpcClient()
40 | if err != nil {
41 | logs.Debug("get rpc client err:%v", err)
42 | ret["code"] = common.ErrorRpcServerError
43 | return
44 | }
45 | defer closeTransport()
46 |
47 | resp, err := rpcClient.GetUserInfoByken(context.Background(), token)
48 | //logs.Debug("user info %v",resp)
49 | if err != nil || resp.Code != rpc.ErrorCode_Success {
50 | logs.Debug("check user token [%v] failed err:%v, resp:%v", token, err, resp)
51 | ret["code"] = common.ErrorAuthFailed
52 | } else {
53 | ret["code"] = int(resp.Code)
54 |
55 | var stakeList []common.InvestUserStake
56 |
57 | err = service.GameConf.MysqlConf.Pool.Select(&stakeList, "select * from game_invest_user_stake where user_id=? and game_times_id=?", resp.UserObj.UserId,gameTimesId)
58 | if err != nil {
59 | logs.Error("select user [%d] stake err:%v", resp.UserObj.UserId, err)
60 | return
61 | }
62 | if len(stakeList) != 1 {
63 | logs.Error("get user [%d],game_tiems_id[%v] record detail api err:%v",resp.UserObj.UserId,gameTimesId,err)
64 | ret["code"] = common.ErrorParamInvalid
65 | return
66 | }
67 | var detail = make([]map[string]interface{},0)
68 | var winItemData = make(map[string]interface{})
69 | var gameResult *common.InvestConf
70 | for _,investConf := range common.InvestConfArr{
71 | if investConf.Id == stakeList[0].GameResult {
72 | gameResult = investConf
73 | break
74 | }
75 | }
76 | stakeDetail := make(map[int]int)
77 | err = json.Unmarshal([]byte(stakeList[0].StakeDetail),&stakeDetail)
78 | if err != nil {
79 | logs.Error("game_times_id [%s] stake detail [%v],json unmarsha1 failed,err:%v",gameTimesId,stakeList[0].StakeDetail,err)
80 | ret["code"] = common.ErrorParamInvalid
81 | return
82 | }
83 | for position,gold := range stakeDetail{
84 | isWinPosition := false
85 | for _,investConf := range gameResult.ParentArr{
86 | if investConf.Id == position {
87 | detail = append(detail,map[string]interface{}{
88 | "item_id" : investConf.Id,
89 | "name" : investConf.Name,
90 | "stake_gold" : gold,
91 | "get_gold" : int(float32(gold) * investConf.Rate),
92 | })
93 | isWinPosition = true
94 | }
95 | }
96 | if !isWinPosition {
97 | for _,investConf := range common.InvestConfArr {
98 | if investConf.Id == position {
99 | detail = append(detail, map[string]interface{}{
100 | "item_id": investConf.Id,
101 | "name": investConf.Name,
102 | "stake_gold": gold,
103 | "get_gold": 0,
104 | })
105 | break
106 | }
107 | }
108 | }
109 | }
110 |
111 | if gameResult == nil {
112 | logs.Error("game_times_id [%s] game result [%d],not invalid",gameTimesId,stakeList[0].GameResult)
113 | ret["code"] = common.ErrorParamInvalid
114 | return
115 | }
116 | if len(gameResult.ParentArr) > 1 {
117 | //填坑, :-(
118 | for k, itemInvestConf := range gameResult.ParentArr {
119 | key := "third_item"
120 | if k == 0 {
121 | key = "third_item"
122 | } else if k == 1 {
123 | key = "second_item"
124 | } else if k == 2 {
125 | key = "first_item"
126 | }
127 | winItemData[key] = map[string]interface{}{
128 | "item_id": itemInvestConf.Id,
129 | "name": itemInvestConf.Name,
130 | "icon": itemInvestConf.Icon,
131 | }
132 | }
133 | } else {
134 | winItemData["first_item"] = map[string]interface{}{}
135 | winItemData["second_item"] = map[string]interface{}{}
136 | winItemData["third_item"] = map[string]interface{}{
137 | "item_id": gameResult.Id,
138 | "name": gameResult.Name,
139 | "icon": gameResult.Icon,
140 | }
141 | }
142 | identityObj := map[string]interface{}{
143 | "userId": resp.UserObj.UserId,
144 | "nickName": resp.UserObj.NickName,
145 | "avatarAuto": resp.UserObj.AvatarAuto,
146 | "sex": 1,
147 | "gold": resp.UserObj.Gold,
148 | "goldenBean": resp.UserObj.Gold,
149 | "diamond": 100000,
150 | "level": 12,
151 | "vipLevel": 1,
152 | }
153 | ret["result"] = map[string]interface{}{
154 | "identity_obj": identityObj,
155 | "record_id":stakeList[0].Periods,
156 | "win_item_data":winItemData,
157 | "detail": detail,
158 | }
159 | }
160 | }
161 |
--------------------------------------------------------------------------------
/invest/common/init.go:
--------------------------------------------------------------------------------
1 | package common
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | const (
8 | CodeSuccess = 0
9 | ErrorAuthFailed = 10000
10 | ErrorParamInvalid = 10001
11 | ErrorUnknownError = 10002
12 | ErrorGoldNotEnough = 10003
13 | ErrorNotStakeTime = 10004
14 | ErrorRpcServerError = 10005
15 | )
16 |
17 | func init() {
18 | for i, investConf := range InvestConfArr {
19 | if investConf.Weight > 0 {
20 | WeightMap[investConf.Id] = investConf.Weight
21 | TotalWeight = TotalWeight + investConf.Weight
22 | if parentsArr, ok := investConf.InitParents(); !ok {
23 | msg := fmt.Sprintf("init investConf [%v] parents,err", investConf)
24 | panic(msg)
25 | } else {
26 | InvestConfArr[i].ParentArr = parentsArr
27 | for _, investConf := range parentsArr { //使用:=声明作用域
28 | InvestConfArr[i].WinPosition = append(InvestConfArr[i].WinPosition, investConf.Id)
29 | }
30 | }
31 | }
32 | RateMap[investConf.Id] = investConf.Rate
33 | }
34 | }
35 |
36 | var (
37 | GameRecord = &Record{
38 | ResultChan: make(chan *InvestConf),
39 | ContinuedWinRecord: make(map[*InvestConf]int), //连续赢的位置
40 | LastTimeWinRecord: make(map[int]int), //距离上一次赢的局数
41 | EverydayResultRecord: &EveryDayRecord{
42 | Record: make(map[*InvestConf]int),
43 | },
44 | }
45 | TotalWeight int
46 | WeightMap = make(map[int]int)
47 | RateMap = make(map[int]float32)
48 | Timer = map[int]int{
49 | 0: StatusPrepare, //游戏间隔
50 | 1: StatusStartStake, //开始押注
51 | 2: StatusSendStake, //发送押注
52 | 28: StatusEndStake, //停止押注,下发当局结果
53 | 33: StatusShowResult, //播放抽奖动画,发下每人盈利
54 | 43: StatusShowWinGold, //结算,并发送非金币
55 | 45: StatusPrepare, //游戏间隔
56 | }
57 | CanStakeChipConf = []*CanStakeChip{
58 | {
59 | GoldMin: 0,
60 | GoldMax: 100000,
61 | Chips: [3]int{100, 500, 1000},
62 | },
63 | {
64 | GoldMin: 100001,
65 | GoldMax: 1000000,
66 | Chips: [3]int{1000, 5000, 20000},
67 | },
68 | {
69 | GoldMin: 1000001,
70 | GoldMax: 10000000,
71 | Chips: [3]int{10000, 20000, 50000},
72 | },
73 | {
74 | GoldMin: 10000001,
75 | GoldMax: -1,
76 | Chips: [3]int{10000, 20000, 50000},
77 | },
78 | }
79 | InvestConfArr = []*InvestConf{
80 | {
81 | Id: 1,
82 | Name: "女装",
83 | ParentId: 13,
84 | Rate: 10,
85 | Weight: 100,
86 | Icon: "tubiao_01",
87 | },
88 | {
89 | Id: 2,
90 | Name: "男装",
91 | ParentId: 13,
92 | Rate: 10,
93 | Weight: 100,
94 | Icon: "tubiao_02",
95 | },
96 | {
97 | Id: 3,
98 | Name: "童装",
99 | ParentId: 13,
100 | Rate: 10,
101 | Weight: 100,
102 | Icon: "tubiao_03",
103 | },
104 | {
105 | Id: 4,
106 | Name: "农机",
107 | ParentId: 14,
108 | Rate: 10,
109 | Weight: 100,
110 | Icon: "tubiao_04",
111 | },
112 | {
113 | Id: 5,
114 | Name: "农药",
115 | ParentId: 14,
116 | Rate: 10,
117 | Weight: 100,
118 | Icon: "tubiao_05",
119 | },
120 | {
121 | Id: 6,
122 | Name: "化肥",
123 | ParentId: 14,
124 | Rate: 10,
125 | Weight: 100,
126 | Icon: "tubiao_06",
127 | },
128 | {
129 | Id: 7,
130 | Name: "影院",
131 | ParentId: 15,
132 | Rate: 10,
133 | Weight: 100,
134 | Icon: "tubiao_07",
135 | },
136 | {
137 | Id: 8,
138 | Name: "KTV",
139 | ParentId: 15,
140 | Rate: 10,
141 | Weight: 100,
142 | Icon: "tubiao_08",
143 | },
144 | {
145 | Id: 9,
146 | Name: "网吧",
147 | ParentId: 15,
148 | Rate: 10,
149 | Weight: 100,
150 | Icon: "tubiao_09",
151 | },
152 | {
153 | Id: 10,
154 | Name: "中餐",
155 | ParentId: 16,
156 | Rate: 10,
157 | Weight: 100,
158 | Icon: "tubiao_10",
159 | },
160 | {
161 | Id: 11,
162 | Name: "西餐",
163 | ParentId: 16,
164 | Rate: 10,
165 | Weight: 100,
166 | Icon: "tubiao_11",
167 | },
168 | {
169 | Id: 12,
170 | Name: "酒吧",
171 | ParentId: 16,
172 | Rate: 10,
173 | Weight: 100,
174 | Icon: "tubiao_12",
175 | },
176 | {
177 | Id: 13,
178 | Name: "服装",
179 | ParentId: 17,
180 | Rate: 3.6,
181 | Weight: 0,
182 | Icon: "tubiao_13",
183 | },
184 | {
185 | Id: 14,
186 | Name: "制造",
187 | ParentId: 17,
188 | Rate: 3.6,
189 | Weight: 0,
190 | Icon: "tubiao_14",
191 | },
192 | {
193 | Id: 15,
194 | Name: "娱乐",
195 | ParentId: 18,
196 | Rate: 3.6,
197 | Weight: 0,
198 | Icon: "tubiao_15",
199 | },
200 | {
201 | Id: 16,
202 | Name: "餐饮",
203 | ParentId: 18,
204 | Rate: 3.6,
205 | Weight: 0,
206 | Icon: "tubiao_16",
207 | },
208 | {
209 | Id: 17,
210 | Name: "工业",
211 | ParentId: 0,
212 | Rate: 1.86,
213 | Weight: 0,
214 | Icon: "tubiao_17",
215 | },
216 | {
217 | Id: 18,
218 | Name: "服务",
219 | ParentId: 0,
220 | Rate: 1.86,
221 | Weight: 0,
222 | Icon: "tubiao_18",
223 | },
224 | {
225 | Id: 19,
226 | Name: "鸿运奖",
227 | ParentId: 0,
228 | Rate: 100,
229 | Weight: 10,
230 | Icon: "tubiao_19",
231 | },
232 | }
233 | )
234 |
--------------------------------------------------------------------------------
/invest/controllers/invest/reward_record.go:
--------------------------------------------------------------------------------
1 | package invest
2 |
3 | import (
4 | "net/http"
5 | "github.com/astaxie/beego/logs"
6 | "encoding/json"
7 | "time"
8 | "game/invest/common"
9 | "game/api/thrift/gen-go/rpc"
10 | "game/invest/tools"
11 | "golang.org/x/net/context"
12 | )
13 |
14 | func RewardRecord(w http.ResponseWriter, r *http.Request) {
15 | defer func() {
16 | //if r := recover(); r != nil {
17 | // logs.Error("RewardRecord panic:%v ", r)
18 | //}
19 | }()
20 | //logs.Debug("new request url:[%s]",r.URL)
21 | ret := make(map[string]interface{})
22 | data := make([]map[string]interface{}, 0)
23 |
24 | ret["time"] = time.Now().Format("2006-01-02 15:04:05")
25 | defer func() {
26 | data, err := json.Marshal(ret)
27 | if err != nil {
28 | logs.Error("json marsha1 failed err:%v", err)
29 | return
30 | }
31 | w.Header().Set("Access-Control-Allow-Origin", "*")
32 | w.Write(data)
33 | }()
34 |
35 | token := r.FormValue("token")
36 | if len(token) == 0 {
37 | token = r.PostFormValue("token")
38 | }
39 | rpcClient, closeTransport, err := tools.GetRpcClient()
40 | if err != nil {
41 | logs.Debug("get rpc client err:%v", err)
42 | ret["code"] = common.ErrorRpcServerError
43 | return
44 | }
45 | defer closeTransport()
46 |
47 | resp, err := rpcClient.GetUserInfoByken(context.Background(), token)
48 | //logs.Debug("user info %v",resp)
49 | if err != nil || resp.Code != rpc.ErrorCode_Success {
50 | logs.Debug("check user token [%v] failed err:%v, resp:%v", token, err, resp)
51 | ret["code"] = common.ErrorAuthFailed
52 | } else {
53 | ret["code"] = int(resp.Code)
54 | identityObj := map[string]interface{}{
55 | "userId": resp.UserObj.UserId,
56 | "nickName": resp.UserObj.NickName,
57 | "avatarAuto": resp.UserObj.AvatarAuto,
58 | "sex": 1,
59 | "gold": resp.UserObj.Gold,
60 | "goldenBean": resp.UserObj.Gold,
61 | "diamond": 100000,
62 | "level": 12,
63 | "vipLevel": 1,
64 | }
65 | result := map[string]interface{}{
66 | "identity_obj": identityObj,
67 | }
68 | reqType := r.FormValue("type")
69 |
70 | common.GameRecord.Lock.RLock()
71 | defer common.GameRecord.Lock.RUnlock()
72 | switch reqType {
73 | case "1":
74 | //logs.Debug("%v",common.GameRecord.LasTTenTimesRank)
75 | //return
76 | for i := len(common.GameRecord.LasTTenTimesRank) - 1; i >= 0; i-- {
77 | rank := common.GameRecord.LasTTenTimesRank[i]
78 | item := make(map[string]interface{})
79 | if rank != nil {
80 | if len(rank.GameResult.ParentArr) > 1 {
81 | //填坑, :-(
82 | for k, itemInvestConf := range rank.GameResult.ParentArr {
83 | key := "third_item"
84 | if k == 0 {
85 | key = "third_item"
86 | } else if k == 1 {
87 | key = "second_item"
88 | } else if k == 2 {
89 | key = "first_item"
90 | }
91 | item[key] = map[string]interface{}{
92 | "item_id": itemInvestConf.Id,
93 | "name": itemInvestConf.Name,
94 | "icon": itemInvestConf.Icon,
95 | }
96 | }
97 | } else {
98 | item["first_item"] = map[string]interface{}{}
99 | item["second_item"] = map[string]interface{}{}
100 | item["third_item"] = map[string]interface{}{
101 | "item_id": rank.GameResult.Id,
102 | "name": rank.GameResult.Name,
103 | "icon": rank.GameResult.Icon,
104 | }
105 | }
106 | data = append(data, item)
107 | }
108 | }
109 | case "2":
110 | for _, investConf := range common.InvestConfArr {
111 | item := make(map[string]interface{})
112 | isSet := false
113 | for investConfId, count := range common.GameRecord.LastTimeWinRecord {
114 | if investConf.Id == investConfId {
115 | item = map[string]interface{}{
116 | "item_id": investConfId,
117 | "name": investConf.Name,
118 | "icon": investConf.Icon,
119 | "count": count,
120 | }
121 | isSet = true
122 | break
123 | }
124 | }
125 | if !isSet {
126 | item = map[string]interface{}{
127 | "item_id": investConf.Id,
128 | "name": investConf.Name,
129 | "icon": investConf.Icon,
130 | "count": -1,
131 | }
132 | }
133 | data = append(data, item)
134 | }
135 | case "3":
136 | for _,investConf := range common.InvestConfArr{
137 | var item map[string]interface{}
138 | if _,ok := common.GameRecord.EverydayResultRecord.Record[investConf];ok {
139 | item = map[string]interface{}{
140 | "item_id" : investConf.Id,
141 | "name" : investConf.Name,
142 | "icon" : investConf.Icon,
143 | "count" : common.GameRecord.EverydayResultRecord.Record[investConf],
144 | }
145 | } else {
146 | item = map[string]interface{}{
147 | "item_id" : investConf.Id,
148 | "name" : investConf.Name,
149 | "icon" : investConf.Icon,
150 | "count" : 0,
151 | }
152 | }
153 | data = append(data,item)
154 | }
155 | case "4":
156 | for _,investConf := range common.InvestConfArr{
157 | var item map[string]interface{}
158 | if _,ok := common.GameRecord.ContinuedWinRecord[investConf];ok {
159 | item = map[string]interface{}{
160 | "item_id" : investConf.Id,
161 | "name" : investConf.Name,
162 | "icon" : investConf.Icon,
163 | "count" : common.GameRecord.ContinuedWinRecord[investConf],
164 | }
165 | } else {
166 | item = map[string]interface{}{
167 | "item_id" : investConf.Id,
168 | "name" : investConf.Name,
169 | "icon" : investConf.Icon,
170 | "count" : 0,
171 | }
172 | }
173 | data = append(data,item)
174 | }
175 | default:
176 | ret["code"] = common.ErrorParamInvalid
177 | return
178 | }
179 | result["data"] = data
180 | ret["result"] = result
181 | ret["msg"] = "请求成功"
182 | }
183 | }
184 |
--------------------------------------------------------------------------------
/ws.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | WebSoket Demo
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
26 |
27 |
28 |
29 |
32 |
33 |
34 |
141 |
--------------------------------------------------------------------------------
/api/thrift/gen-go/rpc/user_service-remote/user_service-remote.go:
--------------------------------------------------------------------------------
1 | // Autogenerated by Thrift Compiler (0.11.0)
2 | // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
3 |
4 | package main
5 |
6 | import (
7 | "context"
8 | "flag"
9 | "fmt"
10 | "math"
11 | "net"
12 | "net/url"
13 | "os"
14 | "strconv"
15 | "strings"
16 | "git.apache.org/thrift.git/lib/go/thrift"
17 | "rpc"
18 | )
19 |
20 |
21 | func Usage() {
22 | fmt.Fprintln(os.Stderr, "Usage of ", os.Args[0], " [-h host:port] [-u url] [-f[ramed]] function [arg1 [arg2...]]:")
23 | flag.PrintDefaults()
24 | fmt.Fprintln(os.Stderr, "\nFunctions:")
25 | fmt.Fprintln(os.Stderr, " Result createNewUser(string nickName, string avatarAuto, i64 gold)")
26 | fmt.Fprintln(os.Stderr, " Result getUserInfoById(i32 userId)")
27 | fmt.Fprintln(os.Stderr, " Result getUserInfoByken(string token)")
28 | fmt.Fprintln(os.Stderr, " Result modifyGoldById(string behavior, i32 userId, i64 gold)")
29 | fmt.Fprintln(os.Stderr, " Result modifyGoldByToken(string behavior, string token, i64 gold)")
30 | fmt.Fprintln(os.Stderr)
31 | os.Exit(0)
32 | }
33 |
34 | func main() {
35 | flag.Usage = Usage
36 | var host string
37 | var port int
38 | var protocol string
39 | var urlString string
40 | var framed bool
41 | var useHttp bool
42 | var parsedUrl *url.URL
43 | var trans thrift.TTransport
44 | _ = strconv.Atoi
45 | _ = math.Abs
46 | flag.Usage = Usage
47 | flag.StringVar(&host, "h", "localhost", "Specify host and port")
48 | flag.IntVar(&port, "p", 9090, "Specify port")
49 | flag.StringVar(&protocol, "P", "binary", "Specify the protocol (binary, compact, simplejson, json)")
50 | flag.StringVar(&urlString, "u", "", "Specify the url")
51 | flag.BoolVar(&framed, "framed", false, "Use framed transport")
52 | flag.BoolVar(&useHttp, "http", false, "Use http")
53 | flag.Parse()
54 |
55 | if len(urlString) > 0 {
56 | var err error
57 | parsedUrl, err = url.Parse(urlString)
58 | if err != nil {
59 | fmt.Fprintln(os.Stderr, "Error parsing URL: ", err)
60 | flag.Usage()
61 | }
62 | host = parsedUrl.Host
63 | useHttp = len(parsedUrl.Scheme) <= 0 || parsedUrl.Scheme == "http"
64 | } else if useHttp {
65 | _, err := url.Parse(fmt.Sprint("http://", host, ":", port))
66 | if err != nil {
67 | fmt.Fprintln(os.Stderr, "Error parsing URL: ", err)
68 | flag.Usage()
69 | }
70 | }
71 |
72 | cmd := flag.Arg(0)
73 | var err error
74 | if useHttp {
75 | trans, err = thrift.NewTHttpClient(parsedUrl.String())
76 | } else {
77 | portStr := fmt.Sprint(port)
78 | if strings.Contains(host, ":") {
79 | host, portStr, err = net.SplitHostPort(host)
80 | if err != nil {
81 | fmt.Fprintln(os.Stderr, "error with host:", err)
82 | os.Exit(1)
83 | }
84 | }
85 | trans, err = thrift.NewTSocket(net.JoinHostPort(host, portStr))
86 | if err != nil {
87 | fmt.Fprintln(os.Stderr, "error resolving address:", err)
88 | os.Exit(1)
89 | }
90 | if framed {
91 | trans = thrift.NewTFramedTransport(trans)
92 | }
93 | }
94 | if err != nil {
95 | fmt.Fprintln(os.Stderr, "Error creating transport", err)
96 | os.Exit(1)
97 | }
98 | defer trans.Close()
99 | var protocolFactory thrift.TProtocolFactory
100 | switch protocol {
101 | case "compact":
102 | protocolFactory = thrift.NewTCompactProtocolFactory()
103 | break
104 | case "simplejson":
105 | protocolFactory = thrift.NewTSimpleJSONProtocolFactory()
106 | break
107 | case "json":
108 | protocolFactory = thrift.NewTJSONProtocolFactory()
109 | break
110 | case "binary", "":
111 | protocolFactory = thrift.NewTBinaryProtocolFactoryDefault()
112 | break
113 | default:
114 | fmt.Fprintln(os.Stderr, "Invalid protocol specified: ", protocol)
115 | Usage()
116 | os.Exit(1)
117 | }
118 | iprot := protocolFactory.GetProtocol(trans)
119 | oprot := protocolFactory.GetProtocol(trans)
120 | client := rpc.NewUserServiceClient(thrift.NewTStandardClient(iprot, oprot))
121 | if err := trans.Open(); err != nil {
122 | fmt.Fprintln(os.Stderr, "Error opening socket to ", host, ":", port, " ", err)
123 | os.Exit(1)
124 | }
125 |
126 | switch cmd {
127 | case "createNewUser":
128 | if flag.NArg() - 1 != 3 {
129 | fmt.Fprintln(os.Stderr, "CreateNewUser requires 3 args")
130 | flag.Usage()
131 | }
132 | argvalue0 := flag.Arg(1)
133 | value0 := argvalue0
134 | argvalue1 := flag.Arg(2)
135 | value1 := argvalue1
136 | argvalue2, err14 := (strconv.ParseInt(flag.Arg(3), 10, 64))
137 | if err14 != nil {
138 | Usage()
139 | return
140 | }
141 | value2 := argvalue2
142 | fmt.Print(client.CreateNewUser(context.Background(), value0, value1, value2))
143 | fmt.Print("\n")
144 | break
145 | case "getUserInfoById":
146 | if flag.NArg() - 1 != 1 {
147 | fmt.Fprintln(os.Stderr, "GetUserInfoById requires 1 args")
148 | flag.Usage()
149 | }
150 | tmp0, err15 := (strconv.Atoi(flag.Arg(1)))
151 | if err15 != nil {
152 | Usage()
153 | return
154 | }
155 | argvalue0 := int32(tmp0)
156 | value0 := argvalue0
157 | fmt.Print(client.GetUserInfoById(context.Background(), value0))
158 | fmt.Print("\n")
159 | break
160 | case "getUserInfoByken":
161 | if flag.NArg() - 1 != 1 {
162 | fmt.Fprintln(os.Stderr, "GetUserInfoByken requires 1 args")
163 | flag.Usage()
164 | }
165 | argvalue0 := flag.Arg(1)
166 | value0 := argvalue0
167 | fmt.Print(client.GetUserInfoByken(context.Background(), value0))
168 | fmt.Print("\n")
169 | break
170 | case "modifyGoldById":
171 | if flag.NArg() - 1 != 3 {
172 | fmt.Fprintln(os.Stderr, "ModifyGoldById requires 3 args")
173 | flag.Usage()
174 | }
175 | argvalue0 := flag.Arg(1)
176 | value0 := argvalue0
177 | tmp1, err18 := (strconv.Atoi(flag.Arg(2)))
178 | if err18 != nil {
179 | Usage()
180 | return
181 | }
182 | argvalue1 := int32(tmp1)
183 | value1 := argvalue1
184 | argvalue2, err19 := (strconv.ParseInt(flag.Arg(3), 10, 64))
185 | if err19 != nil {
186 | Usage()
187 | return
188 | }
189 | value2 := argvalue2
190 | fmt.Print(client.ModifyGoldById(context.Background(), value0, value1, value2))
191 | fmt.Print("\n")
192 | break
193 | case "modifyGoldByToken":
194 | if flag.NArg() - 1 != 3 {
195 | fmt.Fprintln(os.Stderr, "ModifyGoldByToken requires 3 args")
196 | flag.Usage()
197 | }
198 | argvalue0 := flag.Arg(1)
199 | value0 := argvalue0
200 | argvalue1 := flag.Arg(2)
201 | value1 := argvalue1
202 | argvalue2, err22 := (strconv.ParseInt(flag.Arg(3), 10, 64))
203 | if err22 != nil {
204 | Usage()
205 | return
206 | }
207 | value2 := argvalue2
208 | fmt.Print(client.ModifyGoldByToken(context.Background(), value0, value1, value2))
209 | fmt.Print("\n")
210 | break
211 | case "":
212 | Usage()
213 | break
214 | default:
215 | fmt.Fprintln(os.Stderr, "Invalid function ", cmd)
216 | }
217 | }
218 |
--------------------------------------------------------------------------------
/invest/service/room.go:
--------------------------------------------------------------------------------
1 | package service
2 |
3 | import (
4 | "sync"
5 | "time"
6 | "github.com/gorilla/websocket"
7 | "fmt"
8 | "game/invest/common"
9 | "encoding/json"
10 | "github.com/gpmgo/gopm/modules/log"
11 | "github.com/astaxie/beego/logs"
12 | "game/invest/tools"
13 | "golang.org/x/net/context"
14 | "game/api/thrift/gen-go/rpc"
15 | )
16 |
17 | type UserPraise struct {
18 | UserId UserId `json:"user_id"`
19 | Num int `json:"num"`
20 | }
21 |
22 | type StakeInfo struct {
23 | Client *Client
24 | Position int
25 | StakeGold int
26 | SuccessCh chan bool
27 | }
28 |
29 | type Room struct {
30 | RoomId RoomId
31 | RoomClients map[UserId]*Client
32 | TeamRadio chan *common.Message
33 | StakeInfoMap map[*Client]map[int]int
34 | WaitSendStakeInfoMap map[*Client]map[int]int
35 | UserStakeChan chan *StakeInfo
36 | LoginOutMap map[UserId]*Client
37 | MemberCount int
38 |
39 | LoginOutChan chan *Client
40 |
41 | PraiseInfo []*UserPraise
42 | Lock sync.RWMutex
43 | }
44 |
45 | func (c *Client) NewRoom() (room *Room) {
46 | c.Hub.RoomIdInr = c.Hub.RoomIdInr + 1
47 | roomClients := map[UserId]*Client{c.UserInfo.UserId: c}
48 | room = &Room{
49 | RoomId: c.Hub.RoomIdInr,
50 | RoomClients: roomClients,
51 | MemberCount: 1,
52 | TeamRadio: make(chan *common.Message, 100),
53 | PraiseInfo: make([]*UserPraise, 0, 5),
54 | StakeInfoMap: make(map[*Client]map[int]int),
55 | WaitSendStakeInfoMap: make(map[*Client]map[int]int),
56 | UserStakeChan: make(chan *StakeInfo, 100),
57 | LoginOutChan: make(chan *Client, 5),
58 | LoginOutMap: make(map[UserId]*Client, 5),
59 | }
60 | c.Room = room
61 | c.Hub.Rooms[room] = 1
62 | c.Hub.UserToRoom[c.UserInfo.UserId] = room
63 | c.Status = clientStatusLogin
64 | go room.roomServer()
65 | logs.Debug("create new room ok!")
66 | return
67 | }
68 |
69 | func (p *Room) IntoRoom(c *Client) (succ bool, err error) {
70 | p.Lock.Lock()
71 | if len(p.RoomClients) > 4 {
72 | err = fmt.Errorf("room already full")
73 | return
74 | }
75 | if _, ok := p.RoomClients[c.UserInfo.UserId]; ok {
76 | err = fmt.Errorf("user already in room")
77 | return
78 | }
79 | p.RoomClients[c.UserInfo.UserId] = c
80 | p.MemberCount++ //人数 +1
81 | p.Lock.Unlock()
82 |
83 | c.Hub.Lock.Lock()
84 | c.Hub.UserToRoom[c.UserInfo.UserId] = p
85 | c.Hub.Rooms[p]++ //人数 +1
86 | c.Hub.Lock.Unlock()
87 |
88 | c.Room = p
89 | c.Status = clientStatusLogin
90 | succ = true
91 | return
92 | }
93 |
94 | func (p *Room) roomServer() {
95 | ticker := time.NewTicker(pingPeriod)
96 | defer func() {
97 | logs.Debug("room [%d] logout ", p.RoomId)
98 | ticker.Stop()
99 | close(p.TeamRadio)
100 | close(p.UserStakeChan)
101 | close(p.LoginOutChan)
102 |
103 | HubMgr.Lock.Lock()
104 | if _, ok := HubMgr.Rooms[p]; ok {
105 | delete(HubMgr.Rooms, p)
106 | } else {
107 | logs.Error("empty room [%d] logout from hub failed", p.RoomId)
108 | }
109 | HubMgr.Lock.Unlock()
110 | }()
111 | for {
112 | select {
113 | case message, ok := <-p.TeamRadio:
114 | if !ok {
115 | for _, Client := range p.RoomClients {
116 | Client.conn.WriteMessage(websocket.CloseMessage, []byte{})
117 | }
118 | logs.Debug("room [%d] team radio close", p.RoomId)
119 | return
120 | }
121 | data := &Message{
122 | NewStake: make(map[string]map[string]int),
123 | }
124 | //logs.Debug("game status %v",message.Type)
125 | switch message.Type {
126 | case common.StatusPrepare:
127 | //处理离线
128 | p.Lock.Lock()
129 | roomUserChange := false
130 | for userId := range p.LoginOutMap {
131 | roomUserChange = true
132 | HubMgr.Lock.Lock()
133 | if _, ok := HubMgr.UserToRoom[userId]; ok {
134 | delete(HubMgr.UserToRoom, userId)
135 | }
136 | if _, ok := HubMgr.LoginOutMap[userId]; ok {
137 | delete(HubMgr.LoginOutMap, userId)
138 | }
139 | HubMgr.Rooms[p]--
140 | HubMgr.Lock.Unlock()
141 | p.MemberCount--
142 | if _, ok := p.RoomClients[userId]; ok { //冗余操作
143 | delete(p.RoomClients, userId)
144 | }
145 | }
146 | p.Lock.Unlock()
147 |
148 | p.Lock.RLock()
149 | if p.MemberCount == 0 {
150 | logs.Debug("room [%d] member count = 0 ,room exit", p.RoomId)
151 | p.Lock.RUnlock()
152 | return
153 | }
154 | if roomUserChange {
155 | //通知其他人
156 | userInRoom := make([]map[string]interface{}, 0)
157 | for _, roomClient := range p.RoomClients {
158 | userInRoom = append(userInRoom, map[string]interface{}{
159 | "user_id": roomClient.UserInfo.UserId,
160 | "nickname": roomClient.UserInfo.Nickname,
161 | "icon": roomClient.UserInfo.Icon,
162 | "gold": roomClient.UserInfo.Gold,
163 | })
164 | }
165 | var noticeUserInRoom = make(map[string]interface{})
166 | noticeUserInRoom["act"] = "room_user_info"
167 | noticeUserInRoom["user_in_room"] = userInRoom
168 | p.sendToRoomMembers(noticeUserInRoom)
169 | }
170 | p.Lock.RUnlock()
171 |
172 | data.Act = "change_state"
173 | data.State = "init"
174 | //初始化数据
175 | p.Lock.Lock()
176 | p.PraiseInfo = make([]*UserPraise, 0, 5)
177 | p.LoginOutMap = make(map[UserId]*Client)
178 | p.StakeInfoMap = make(map[*Client]map[int]int)
179 | p.WaitSendStakeInfoMap = make(map[*Client]map[int]int)
180 | p.Lock.Unlock()
181 |
182 | case common.StatusStartStake:
183 | data.Act = "change_state"
184 | data.State = "staking"
185 | data.Timer = 27
186 | HubMgr.GameManage.Lock.RLock()
187 | data.Periods = HubMgr.GameManage.Periods
188 | HubMgr.GameManage.Lock.RUnlock()
189 | case common.StatusSendStake:
190 | //发送加油
191 | p.Lock.RLock()
192 | if len(p.PraiseInfo) != 0 {
193 | praiseMsg := map[string]interface{}{
194 | "act": "praise_info",
195 | "praise_info": p.PraiseInfo,
196 | "timer": HubMgr.GameManage.StakeCountdown,
197 | }
198 | p.sendToRoomMembers(praiseMsg)
199 | p.PraiseInfo = make([]*UserPraise, 0, 5)
200 | }
201 | p.Lock.RUnlock()
202 |
203 | //logs.Debug("WaitSendStakeInfoMap:%v",p.WaitSendStakeInfoMap)
204 | //logs.Debug("StakeInfoMap:%v",p.StakeInfoMap)
205 |
206 | data.Act = "stake_info"
207 | HubMgr.GameManage.Lock.RLock()
208 | data.Timer = HubMgr.GameManage.StakeCountdown
209 | HubMgr.GameManage.Lock.RUnlock()
210 | HubMgr.GameInfo.Lock.RLock()
211 | data.Pool = HubMgr.GameInfo.Pool
212 | HubMgr.GameInfo.Lock.RUnlock()
213 |
214 | p.Lock.RLock()
215 | for client, stakeMap := range p.WaitSendStakeInfoMap {
216 | key := fmt.Sprintf("user_%d", client.UserInfo.UserId)
217 | var userNewStake = make(map[string]int)
218 | for position, gold := range stakeMap {
219 | field := fmt.Sprintf("position_%d", position)
220 | userNewStake[field] = gold
221 | }
222 | data.NewStake[key] = userNewStake
223 | }
224 | stake := make(map[int]int)
225 | for _, stakeMap := range p.StakeInfoMap {
226 | for position, gold := range stakeMap {
227 | if stakeGold, ok := stake[position]; ok {
228 | stake[position] = stakeGold + gold
229 | } else {
230 | stake[position] = gold
231 | }
232 | }
233 | }
234 | p.Lock.RUnlock()
235 |
236 | for position, gold := range stake {
237 | data.StakeInfo = append(data.StakeInfo, map[string]int{"position": position, "stake_gold": gold})
238 | }
239 | //清空代发消息
240 | p.Lock.Lock()
241 | p.WaitSendStakeInfoMap = make(map[*Client]map[int]int)
242 | p.Lock.Unlock()
243 |
244 | if len(data.NewStake) == 0 {
245 | continue
246 | }
247 |
248 | case common.StatusEndStake:
249 | data.Act = "change_state"
250 | data.State = "endstake"
251 | case common.StatusSendResult:
252 | //这儿是之前留的坑,两个不同的字段用了同一个name,故改用map
253 | HubMgr.GameInfo.Lock.RLock()
254 | gameResult := map[string]interface{}{
255 | "act": "push_result",
256 | "win_result": HubMgr.GameInfo.GameResult.Id,
257 | "win_position": HubMgr.GameInfo.GameResult.WinPosition,
258 | }
259 | HubMgr.GameInfo.Lock.RUnlock()
260 | p.Lock.RLock()
261 | p.sendToRoomMembers(gameResult)
262 | p.Lock.RUnlock()
263 | //continue
264 | case common.StatusShowResult:
265 | data.Act = "change_state"
266 | data.State = "show_result"
267 | case common.StatusShowWinGold:
268 | data.Act = "change_state"
269 | data.State = "show_win_result"
270 | }
271 | if message.Type != common.StatusSendResult {
272 | p.Lock.RLock()
273 | p.sendToRoomMembers(data)
274 | p.Lock.RUnlock()
275 | } else { //结算
276 | data = &Message{
277 | Act: "send_room_win_result",
278 | }
279 | p.Lock.RLock()
280 | HubMgr.GameInfo.Lock.RLock()
281 |
282 | for userId, client := range p.RoomClients {
283 | userWInResult := &UserWinResult{
284 | UserId: userId,
285 | }
286 | for _, positionId := range HubMgr.GameInfo.GameResult.WinPosition {
287 | if stakeGold, ok := p.StakeInfoMap[client][positionId]; ok {
288 | if rate, ok := common.RateMap[positionId]; ok {
289 | userWInResult.WinGold = userWInResult.WinGold + int(float32(stakeGold)*rate)
290 | } else {
291 | logs.Error("read position [%d] rate failed ", positionId)
292 | }
293 | }
294 | }
295 | if userWInResult.WinGold > 0 {
296 | data.UserWinResult = append(data.UserWinResult, userWInResult)
297 | }
298 | }
299 | //处理离线用户盈利
300 | for userId, client := range p.LoginOutMap {
301 | userWInResult := &UserWinResult{
302 | UserId: userId,
303 | }
304 | for _, positionId := range HubMgr.GameInfo.GameResult.WinPosition {
305 | if stakeGold, ok := p.StakeInfoMap[client][positionId]; ok {
306 | if rate, ok := common.RateMap[positionId]; ok {
307 | userWInResult.WinGold = userWInResult.WinGold + int(float32(stakeGold)*rate)
308 | } else {
309 | logs.Error("read position [%d] rate failed ", positionId)
310 | }
311 | }
312 | }
313 | if userWInResult.WinGold > 0 {
314 | data.UserWinResult = append(data.UserWinResult, userWInResult)
315 | }
316 | }
317 | p.Lock.RUnlock()
318 | HubMgr.GameInfo.Lock.RUnlock()
319 |
320 | if len(data.UserWinResult) > 0 {
321 | p.Lock.RLock()
322 | p.sendToRoomMembers(data)
323 | p.Lock.RUnlock()
324 | go p.addWinGold(data.UserWinResult)
325 | }
326 | //log.Debug("send_room_win_result:%v", data.UserWinResult)
327 | }
328 | case <-ticker.C: //心跳
329 | for _, Client := range p.RoomClients {
330 | Client.conn.SetWriteDeadline(time.Now().Add(writeWait))
331 | if err := Client.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
332 | Client.conn.Close()
333 | p.LoginOutChan <- Client
334 | }
335 | }
336 | case cli := <-p.LoginOutChan:
337 | p.Lock.Lock()
338 | if _, ok := p.LoginOutMap[cli.UserInfo.UserId]; ok {
339 | p.Lock.Unlock()
340 | continue
341 | }
342 | p.LoginOutMap[cli.UserInfo.UserId] = cli
343 | if _, ok := p.RoomClients[cli.UserInfo.UserId]; ok {
344 | delete(p.RoomClients, cli.UserInfo.UserId)
345 | }
346 | p.Lock.Unlock()
347 |
348 | HubMgr.Lock.Lock()
349 | HubMgr.LoginOutMap[cli.UserInfo.UserId] = cli
350 | delete(HubMgr.UserToRoom, cli.UserInfo.UserId)
351 | HubMgr.Lock.Unlock()
352 |
353 | case stakeInfo := <-p.UserStakeChan:
354 | //logs.Debug("user [%d] stake gold : %d,position:%d", stakeInfo.Client.UserInfo.UserId, stakeInfo.StakeGold, stakeInfo.Position)
355 | HubMgr.GameManage.Lock.RLock()
356 | if HubMgr.GameManage.GameStatus == common.StatusStartStake || HubMgr.GameManage.GameStatus == common.StatusSendStake {
357 | if stakeInfoMap, ok := p.StakeInfoMap[stakeInfo.Client]; ok {
358 | if positionStakeMap, ok := stakeInfoMap[stakeInfo.Position]; ok {
359 | p.StakeInfoMap[stakeInfo.Client][stakeInfo.Position] = positionStakeMap + stakeInfo.StakeGold
360 | } else {
361 | p.StakeInfoMap[stakeInfo.Client][stakeInfo.Position] = stakeInfo.StakeGold
362 | }
363 | } else {
364 | p.StakeInfoMap[stakeInfo.Client] = map[int]int{stakeInfo.Position: stakeInfo.StakeGold}
365 | }
366 |
367 | if stakeInfoMap, ok := p.WaitSendStakeInfoMap[stakeInfo.Client]; ok {
368 | if positionStakeMap, ok := stakeInfoMap[stakeInfo.Position]; ok {
369 | p.WaitSendStakeInfoMap[stakeInfo.Client][stakeInfo.Position] = positionStakeMap + stakeInfo.StakeGold
370 | } else {
371 | p.WaitSendStakeInfoMap[stakeInfo.Client][stakeInfo.Position] = stakeInfo.StakeGold
372 | }
373 | } else {
374 | p.WaitSendStakeInfoMap[stakeInfo.Client] = map[int]int{stakeInfo.Position: stakeInfo.StakeGold}
375 | }
376 | HubMgr.GameInfo.Lock.Lock()
377 | if totalStake, ok := HubMgr.GameInfo.StakeMap[stakeInfo.Position]; ok {
378 | HubMgr.GameInfo.StakeMap[stakeInfo.Position] = totalStake + stakeInfo.StakeGold
379 | } else {
380 | HubMgr.GameInfo.StakeMap[stakeInfo.Position] = stakeInfo.StakeGold
381 | }
382 | HubMgr.GameInfo.Pool = HubMgr.GameInfo.Pool + stakeInfo.StakeGold*(100-GameConf.PumpingRate)/100
383 | HubMgr.GameInfo.Lock.Unlock()
384 | HubMgr.GameManage.Lock.RUnlock()
385 | stakeInfo.SuccessCh <- true
386 |
387 | } else {
388 | stakeInfo.SuccessCh <- false
389 | HubMgr.GameManage.Lock.RUnlock()
390 | }
391 | }
392 | }
393 | }
394 |
395 | func (p *Room) sendToRoomMembers(data interface{}) {
396 | //logs.Debug("room send to members message %v", data)
397 | msg, err := json.Marshal(data)
398 | if err != nil {
399 | log.Error("send room win result data marsha1 err:%v", err)
400 | }
401 | for _, Client := range p.RoomClients {
402 | Client.sendMsg(msg)
403 | }
404 | }
405 |
406 | func (p *Room) addWinGold(userWinResult []*UserWinResult) {
407 | HubMgr.GameInfo.Lock.RLock()
408 | periods := HubMgr.GameInfo.Periods
409 | pool := HubMgr.GameInfo.Pool
410 | gameResult := HubMgr.GameInfo.GameResult.Id
411 | HubMgr.GameInfo.Lock.RUnlock()
412 | HubMgr.GameManage.Lock.RLock()
413 | gameTimesId := HubMgr.GameManage.TimesId
414 | HubMgr.GameManage.Lock.RUnlock()
415 | stakeTime := time.Now().Format("2006-01-02 15:04:05")
416 | client, closeTransportHandler, err := tools.GetRpcClient()
417 | defer closeTransportHandler()
418 | if err != nil {
419 | logs.Error("get rpc client err:%v,add user win gold failed :%v", err, userWinResult)
420 | return
421 | }
422 |
423 | for _, winResult := range userWinResult {
424 | resp, err := client.ModifyGoldById(context.Background(), "invest win gold", int32(winResult.UserId), int64(winResult.WinGold))
425 | if err != nil || resp.Code != rpc.ErrorCode_Success {
426 | logs.Error("user [%d] win gold [%v] add failed err:%v", winResult.UserId, winResult.WinGold, err)
427 | }
428 | }
429 |
430 | //持久化
431 | conn := GameConf.RedisConf.RedisPool.Get()
432 | defer conn.Close()
433 | //todo 完善
434 | for client, stakeGoldMap := range p.StakeInfoMap {
435 | var userAllStake, winGold int
436 | for _, stakeGold := range stakeGoldMap {
437 | userAllStake = userAllStake + stakeGold
438 | }
439 | for _, userWin := range userWinResult {
440 | if userWin.UserId == client.UserInfo.UserId {
441 | winGold = winGold + userWin.WinGold
442 | }
443 | }
444 | stakeDetail, err := json.Marshal(stakeGoldMap)
445 | if err != nil {
446 | logs.Error("json marsha1 user stake detail [%v] err:%v", stakeGoldMap, err)
447 | stakeDetail = []byte{}
448 | }
449 | data := common.InvestUserStake{
450 | GameTimesId: gameTimesId,
451 | Periods: periods,
452 | RoomId: int(p.RoomId),
453 | RoomType: 0,
454 | UserId: int(client.UserInfo.UserId),
455 | Nickname: client.UserInfo.Nickname,
456 | UserAllStake: userAllStake,
457 | WinGold: winGold,
458 | StakeDetail: string(stakeDetail),
459 | GameResult: gameResult,
460 | Pool: pool,
461 | StakeTime: stakeTime,
462 | }
463 |
464 | dataStr, err := json.Marshal(data)
465 | if err != nil {
466 | logs.Error("json marsha1 user stake msg err:%v", err)
467 | return
468 | }
469 | //logs.Debug("lPush [%v] total user stake msg [%v]", GameConf.RedisKey.RedisKeyUserStake,string(dataStr))
470 | _,err = conn.Do("lPush", GameConf.RedisKey.RedisKeyUserStake, string(dataStr))
471 | if err != nil {
472 | logs.Error("lPush user stake msg [%v] err:%v",GameConf.RedisKey.RedisKeyUserStake,err)
473 | }
474 | }
475 | }
476 |
477 | //调用处外层 已对 hubMgr 加锁 (读锁)
478 | func (p *Room) UserLoginResponse(client *Client) {
479 | //协程内发送,避免读锁长时间不能释放
480 | var sendLoginResult = func() {}
481 | var sendOtherMembers = func() {}
482 | var sendEndStake = func() {}
483 | var sendPushResult = func() {}
484 | var sendRoomWinResult = func() {}
485 | var sendShowResult = func() {}
486 | defer func() {
487 | go func() {
488 | sendLoginResult()
489 | sendOtherMembers()
490 | sendEndStake()
491 | sendPushResult()
492 | sendRoomWinResult()
493 | sendShowResult()
494 | }()
495 | }()
496 |
497 | p.Lock.RLock()
498 | defer p.Lock.RUnlock()
499 |
500 | var data = make(map[string]interface{})
501 | data["act"] = "login_result"
502 | data["user_obj"] = map[string]interface{}{
503 | "userId": client.UserInfo.UserId,
504 | "nickName": client.UserInfo.Nickname,
505 | "avatarAuto": client.UserInfo.Icon,
506 | "sex": 1,
507 | "gold": client.UserInfo.Gold,
508 | "goldenBean": client.UserInfo.Gold,
509 | "diamond": 100000,
510 | "level": 12,
511 | "vipLevel": 1,
512 | }
513 |
514 | if stakeInfoMap, ok := p.StakeInfoMap[client]; ok {
515 | selfStake := make([]map[string]int, 0)
516 | for positionId, stakeGold := range stakeInfoMap {
517 | stakeItem := map[string]int{"position": positionId, "stake_gold": stakeGold}
518 | selfStake = append(selfStake, stakeItem)
519 | }
520 | data["self_stake"] = selfStake
521 | }
522 |
523 | stakeInfo := make(map[int]int, 0)
524 | for _, stakeInfoItem := range p.StakeInfoMap {
525 | for position, stakeGold := range stakeInfoItem {
526 | if _, ok := stakeInfo[position]; ok {
527 | stakeInfo[position] = stakeInfo[position] + stakeGold
528 | } else {
529 | stakeInfo[position] = stakeGold
530 | }
531 | }
532 | }
533 |
534 | stakeInfoMap := make([]map[string]int, 0)
535 | for position, stakeGold := range stakeInfo {
536 | stakeInfoMapItem := map[string]int{
537 | "position": position,
538 | "stake_gold": stakeGold,
539 | }
540 | stakeInfoMap = append(stakeInfoMap, stakeInfoMapItem)
541 | }
542 | data["stake_info"] = stakeInfoMap
543 |
544 | userInRoom := make([]map[string]interface{}, 0)
545 | for _, roomClient := range p.RoomClients {
546 | userInRoom = append(userInRoom, map[string]interface{}{
547 | "user_id": roomClient.UserInfo.UserId,
548 | "nickname": roomClient.UserInfo.Nickname,
549 | "icon": roomClient.UserInfo.Icon,
550 | "gold": roomClient.UserInfo.Gold,
551 | })
552 | }
553 | for _, roomClient := range p.LoginOutMap {
554 | userInRoom = append(userInRoom, map[string]interface{}{
555 | "user_id": roomClient.UserInfo.UserId,
556 | "nickname": roomClient.UserInfo.Nickname,
557 | "icon": roomClient.UserInfo.Icon,
558 | "gold": roomClient.UserInfo.Gold,
559 | })
560 | }
561 | data["user_in_room"] = userInRoom
562 |
563 | HubMgr.GameInfo.Lock.RLock()
564 | defer HubMgr.GameInfo.Lock.RUnlock()
565 | data["last_win_result"] = HubMgr.GameInfo.GameResult.Id
566 | data["pool"] = HubMgr.GameInfo.Pool
567 | data["periods"] = HubMgr.GameInfo.Periods
568 |
569 | data["chips_config"] = common.CanStakeChipConf
570 | HubMgr.GameManage.Lock.RLock()
571 | defer HubMgr.GameManage.Lock.RUnlock()
572 | data["timer"] = HubMgr.GameManage.StakeCountdown
573 |
574 | loginResultMsg, err := json.Marshal(data)
575 | if err != nil {
576 | log.Error("send room win result data marsha1 err:%v", err)
577 | return
578 | }
579 | sendLoginResult = func() {
580 | client.sendMsg(loginResultMsg)
581 | }
582 |
583 | //通知其他人
584 | var NoticeOthers = make(map[string]interface{})
585 | NoticeOthers["act"] = "room_user_info"
586 | NoticeOthers["user_in_room"] = data["user_in_room"]
587 | sendOtherMembersMsg, err := json.Marshal(NoticeOthers)
588 | if err != nil {
589 | log.Error("send room win result data marsha1 err:%v", err)
590 | return
591 | }
592 | sendOtherMembers = func() {
593 | p.Lock.RLock()
594 | defer p.Lock.RUnlock()
595 | for _, roomClient := range p.RoomClients {
596 | if roomClient != client {
597 | roomClient.sendMsg(sendOtherMembersMsg)
598 | }
599 | }
600 | }
601 |
602 | //流畅性处理
603 | if HubMgr.GameManage.GameStatus == common.StatusEndStake || HubMgr.GameManage.GameStatus == common.StatusShowResult {
604 | if HubMgr.GameManage.GameStatus == common.StatusEndStake {
605 | data := &Message{
606 | Act: "change_state",
607 | State: "endstake",
608 | }
609 | endStakeMsg, err := json.Marshal(data)
610 | if err != nil {
611 | log.Error("send room win result data marsha1 err:%v", err)
612 | return
613 | }
614 | sendEndStake = func() {
615 | client.sendMsg(endStakeMsg)
616 | }
617 | }
618 |
619 | gameResult := map[string]interface{}{
620 | "act": "push_result",
621 | "win_result": HubMgr.GameInfo.GameResult.Id,
622 | "win_position": HubMgr.GameInfo.GameResult.WinPosition,
623 | }
624 | pushResultMsg, err := json.Marshal(gameResult)
625 | if err != nil {
626 | log.Error("send room win result data marsha1 err:%v", err)
627 | return
628 | }
629 | sendPushResult = func() {
630 | client.sendMsg(pushResultMsg)
631 | }
632 |
633 | data := &Message{
634 | Act: "send_room_win_result",
635 | NewStake: make(map[string]map[string]int),
636 | }
637 | for userId, client := range p.RoomClients {
638 | userWInResult := &UserWinResult{
639 | UserId: userId,
640 | }
641 | for _, positionId := range HubMgr.GameInfo.GameResult.WinPosition {
642 | if stakeGold, ok := p.StakeInfoMap[client][positionId]; ok {
643 | if rate, ok := common.RateMap[positionId]; ok {
644 | userWInResult.WinGold = userWInResult.WinGold + int(float32(stakeGold)*rate)
645 | } else {
646 | logs.Error("read position [%d] rate failed ", positionId)
647 | }
648 | }
649 | }
650 | if userWInResult.WinGold > 0 {
651 | data.UserWinResult = append(data.UserWinResult, userWInResult)
652 | }
653 | }
654 | if len(data.UserWinResult) > 0 {
655 | roomWinResultMsg, err := json.Marshal(data)
656 | if err != nil {
657 | log.Error("send room win result data marsha1 err:%v", err)
658 | return
659 | }
660 | sendRoomWinResult = func() {
661 | client.sendMsg(roomWinResultMsg)
662 | }
663 | }
664 |
665 | if HubMgr.GameManage.GameStatus == common.StatusShowResult {
666 | data := &Message{
667 | Act: "change_state",
668 | State: "show_result",
669 | }
670 | showResultMsg, err := json.Marshal(data)
671 | if err != nil {
672 | log.Error("send room win result data marsha1 err:%v", err)
673 | return
674 | }
675 | sendShowResult = func() {
676 | client.sendMsg(showResultMsg)
677 | }
678 | }
679 | }
680 | }
681 |
--------------------------------------------------------------------------------
/api/thrift/gen-go/rpc/user.go:
--------------------------------------------------------------------------------
1 | // Autogenerated by Thrift Compiler (0.11.0)
2 | // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
3 |
4 | package rpc
5 |
6 | import (
7 | "bytes"
8 | "reflect"
9 | "database/sql/driver"
10 | "errors"
11 | "context"
12 | "fmt"
13 | "git.apache.org/thrift.git/lib/go/thrift"
14 | )
15 |
16 | // (needed to ensure safety because of naive import list construction.)
17 | var _ = thrift.ZERO
18 | var _ = fmt.Printf
19 | var _ = context.Background
20 | var _ = reflect.DeepEqual
21 | var _ = bytes.Equal
22 |
23 | type ErrorCode int64
24 | const (
25 | ErrorCode_Success ErrorCode = 0
26 | ErrorCode_UnknowError ErrorCode = 5000
27 | ErrorCode_VerifyError ErrorCode = 5001
28 | ErrorCode_UserIsNull ErrorCode = 5002
29 | ErrorCode_AddUserFail ErrorCode = 5005
30 | ErrorCode_UserBeKickOff ErrorCode = 5006
31 | ErrorCode_GoldNotEnough ErrorCode = 5007
32 | ErrorCode_DiamondNotEnough ErrorCode = 5009
33 | )
34 |
35 | func (p ErrorCode) String() string {
36 | switch p {
37 | case ErrorCode_Success: return "Success"
38 | case ErrorCode_UnknowError: return "UnknowError"
39 | case ErrorCode_VerifyError: return "VerifyError"
40 | case ErrorCode_UserIsNull: return "UserIsNull"
41 | case ErrorCode_AddUserFail: return "AddUserFail"
42 | case ErrorCode_UserBeKickOff: return "UserBeKickOff"
43 | case ErrorCode_GoldNotEnough: return "GoldNotEnough"
44 | case ErrorCode_DiamondNotEnough: return "DiamondNotEnough"
45 | }
46 | return ""
47 | }
48 |
49 | func ErrorCodeFromString(s string) (ErrorCode, error) {
50 | switch s {
51 | case "Success": return ErrorCode_Success, nil
52 | case "UnknowError": return ErrorCode_UnknowError, nil
53 | case "VerifyError": return ErrorCode_VerifyError, nil
54 | case "UserIsNull": return ErrorCode_UserIsNull, nil
55 | case "AddUserFail": return ErrorCode_AddUserFail, nil
56 | case "UserBeKickOff": return ErrorCode_UserBeKickOff, nil
57 | case "GoldNotEnough": return ErrorCode_GoldNotEnough, nil
58 | case "DiamondNotEnough": return ErrorCode_DiamondNotEnough, nil
59 | }
60 | return ErrorCode(0), fmt.Errorf("not a valid ErrorCode string")
61 | }
62 |
63 |
64 | func ErrorCodePtr(v ErrorCode) *ErrorCode { return &v }
65 |
66 | func (p ErrorCode) MarshalText() ([]byte, error) {
67 | return []byte(p.String()), nil
68 | }
69 |
70 | func (p *ErrorCode) UnmarshalText(text []byte) error {
71 | q, err := ErrorCodeFromString(string(text))
72 | if (err != nil) {
73 | return err
74 | }
75 | *p = q
76 | return nil
77 | }
78 |
79 | func (p *ErrorCode) Scan(value interface{}) error {
80 | v, ok := value.(int64)
81 | if !ok {
82 | return errors.New("Scan value is not int64")
83 | }
84 | *p = ErrorCode(v)
85 | return nil
86 | }
87 |
88 | func (p * ErrorCode) Value() (driver.Value, error) {
89 | if p == nil {
90 | return nil, nil
91 | }
92 | return int64(*p), nil
93 | }
94 | // Attributes:
95 | // - UserId
96 | // - UserName
97 | // - NickName
98 | // - AvatarAuto
99 | // - Gold
100 | // - Token
101 | type UserInfo struct {
102 | UserId int64 `thrift:"userId,1" db:"userId" json:"userId"`
103 | UserName string `thrift:"userName,2" db:"userName" json:"userName"`
104 | NickName string `thrift:"nickName,3" db:"nickName" json:"nickName"`
105 | AvatarAuto string `thrift:"avatarAuto,4" db:"avatarAuto" json:"avatarAuto"`
106 | Gold int64 `thrift:"gold,5" db:"gold" json:"gold"`
107 | Token string `thrift:"token,6" db:"token" json:"token"`
108 | }
109 |
110 | func NewUserInfo() *UserInfo {
111 | return &UserInfo{}
112 | }
113 |
114 |
115 | func (p *UserInfo) GetUserId() int64 {
116 | return p.UserId
117 | }
118 |
119 | func (p *UserInfo) GetUserName() string {
120 | return p.UserName
121 | }
122 |
123 | func (p *UserInfo) GetNickName() string {
124 | return p.NickName
125 | }
126 |
127 | func (p *UserInfo) GetAvatarAuto() string {
128 | return p.AvatarAuto
129 | }
130 |
131 | func (p *UserInfo) GetGold() int64 {
132 | return p.Gold
133 | }
134 |
135 | func (p *UserInfo) GetToken() string {
136 | return p.Token
137 | }
138 | func (p *UserInfo) Read(iprot thrift.TProtocol) error {
139 | if _, err := iprot.ReadStructBegin(); err != nil {
140 | return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
141 | }
142 |
143 |
144 | for {
145 | _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
146 | if err != nil {
147 | return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
148 | }
149 | if fieldTypeId == thrift.STOP { break; }
150 | switch fieldId {
151 | case 1:
152 | if fieldTypeId == thrift.I64 {
153 | if err := p.ReadField1(iprot); err != nil {
154 | return err
155 | }
156 | } else {
157 | if err := iprot.Skip(fieldTypeId); err != nil {
158 | return err
159 | }
160 | }
161 | case 2:
162 | if fieldTypeId == thrift.STRING {
163 | if err := p.ReadField2(iprot); err != nil {
164 | return err
165 | }
166 | } else {
167 | if err := iprot.Skip(fieldTypeId); err != nil {
168 | return err
169 | }
170 | }
171 | case 3:
172 | if fieldTypeId == thrift.STRING {
173 | if err := p.ReadField3(iprot); err != nil {
174 | return err
175 | }
176 | } else {
177 | if err := iprot.Skip(fieldTypeId); err != nil {
178 | return err
179 | }
180 | }
181 | case 4:
182 | if fieldTypeId == thrift.STRING {
183 | if err := p.ReadField4(iprot); err != nil {
184 | return err
185 | }
186 | } else {
187 | if err := iprot.Skip(fieldTypeId); err != nil {
188 | return err
189 | }
190 | }
191 | case 5:
192 | if fieldTypeId == thrift.I64 {
193 | if err := p.ReadField5(iprot); err != nil {
194 | return err
195 | }
196 | } else {
197 | if err := iprot.Skip(fieldTypeId); err != nil {
198 | return err
199 | }
200 | }
201 | case 6:
202 | if fieldTypeId == thrift.STRING {
203 | if err := p.ReadField6(iprot); err != nil {
204 | return err
205 | }
206 | } else {
207 | if err := iprot.Skip(fieldTypeId); err != nil {
208 | return err
209 | }
210 | }
211 | default:
212 | if err := iprot.Skip(fieldTypeId); err != nil {
213 | return err
214 | }
215 | }
216 | if err := iprot.ReadFieldEnd(); err != nil {
217 | return err
218 | }
219 | }
220 | if err := iprot.ReadStructEnd(); err != nil {
221 | return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
222 | }
223 | return nil
224 | }
225 |
226 | func (p *UserInfo) ReadField1(iprot thrift.TProtocol) error {
227 | if v, err := iprot.ReadI64(); err != nil {
228 | return thrift.PrependError("error reading field 1: ", err)
229 | } else {
230 | p.UserId = v
231 | }
232 | return nil
233 | }
234 |
235 | func (p *UserInfo) ReadField2(iprot thrift.TProtocol) error {
236 | if v, err := iprot.ReadString(); err != nil {
237 | return thrift.PrependError("error reading field 2: ", err)
238 | } else {
239 | p.UserName = v
240 | }
241 | return nil
242 | }
243 |
244 | func (p *UserInfo) ReadField3(iprot thrift.TProtocol) error {
245 | if v, err := iprot.ReadString(); err != nil {
246 | return thrift.PrependError("error reading field 3: ", err)
247 | } else {
248 | p.NickName = v
249 | }
250 | return nil
251 | }
252 |
253 | func (p *UserInfo) ReadField4(iprot thrift.TProtocol) error {
254 | if v, err := iprot.ReadString(); err != nil {
255 | return thrift.PrependError("error reading field 4: ", err)
256 | } else {
257 | p.AvatarAuto = v
258 | }
259 | return nil
260 | }
261 |
262 | func (p *UserInfo) ReadField5(iprot thrift.TProtocol) error {
263 | if v, err := iprot.ReadI64(); err != nil {
264 | return thrift.PrependError("error reading field 5: ", err)
265 | } else {
266 | p.Gold = v
267 | }
268 | return nil
269 | }
270 |
271 | func (p *UserInfo) ReadField6(iprot thrift.TProtocol) error {
272 | if v, err := iprot.ReadString(); err != nil {
273 | return thrift.PrependError("error reading field 6: ", err)
274 | } else {
275 | p.Token = v
276 | }
277 | return nil
278 | }
279 |
280 | func (p *UserInfo) Write(oprot thrift.TProtocol) error {
281 | if err := oprot.WriteStructBegin("UserInfo"); err != nil {
282 | return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) }
283 | if p != nil {
284 | if err := p.writeField1(oprot); err != nil { return err }
285 | if err := p.writeField2(oprot); err != nil { return err }
286 | if err := p.writeField3(oprot); err != nil { return err }
287 | if err := p.writeField4(oprot); err != nil { return err }
288 | if err := p.writeField5(oprot); err != nil { return err }
289 | if err := p.writeField6(oprot); err != nil { return err }
290 | }
291 | if err := oprot.WriteFieldStop(); err != nil {
292 | return thrift.PrependError("write field stop error: ", err) }
293 | if err := oprot.WriteStructEnd(); err != nil {
294 | return thrift.PrependError("write struct stop error: ", err) }
295 | return nil
296 | }
297 |
298 | func (p *UserInfo) writeField1(oprot thrift.TProtocol) (err error) {
299 | if err := oprot.WriteFieldBegin("userId", thrift.I64, 1); err != nil {
300 | return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:userId: ", p), err) }
301 | if err := oprot.WriteI64(int64(p.UserId)); err != nil {
302 | return thrift.PrependError(fmt.Sprintf("%T.userId (1) field write error: ", p), err) }
303 | if err := oprot.WriteFieldEnd(); err != nil {
304 | return thrift.PrependError(fmt.Sprintf("%T write field end error 1:userId: ", p), err) }
305 | return err
306 | }
307 |
308 | func (p *UserInfo) writeField2(oprot thrift.TProtocol) (err error) {
309 | if err := oprot.WriteFieldBegin("userName", thrift.STRING, 2); err != nil {
310 | return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:userName: ", p), err) }
311 | if err := oprot.WriteString(string(p.UserName)); err != nil {
312 | return thrift.PrependError(fmt.Sprintf("%T.userName (2) field write error: ", p), err) }
313 | if err := oprot.WriteFieldEnd(); err != nil {
314 | return thrift.PrependError(fmt.Sprintf("%T write field end error 2:userName: ", p), err) }
315 | return err
316 | }
317 |
318 | func (p *UserInfo) writeField3(oprot thrift.TProtocol) (err error) {
319 | if err := oprot.WriteFieldBegin("nickName", thrift.STRING, 3); err != nil {
320 | return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:nickName: ", p), err) }
321 | if err := oprot.WriteString(string(p.NickName)); err != nil {
322 | return thrift.PrependError(fmt.Sprintf("%T.nickName (3) field write error: ", p), err) }
323 | if err := oprot.WriteFieldEnd(); err != nil {
324 | return thrift.PrependError(fmt.Sprintf("%T write field end error 3:nickName: ", p), err) }
325 | return err
326 | }
327 |
328 | func (p *UserInfo) writeField4(oprot thrift.TProtocol) (err error) {
329 | if err := oprot.WriteFieldBegin("avatarAuto", thrift.STRING, 4); err != nil {
330 | return thrift.PrependError(fmt.Sprintf("%T write field begin error 4:avatarAuto: ", p), err) }
331 | if err := oprot.WriteString(string(p.AvatarAuto)); err != nil {
332 | return thrift.PrependError(fmt.Sprintf("%T.avatarAuto (4) field write error: ", p), err) }
333 | if err := oprot.WriteFieldEnd(); err != nil {
334 | return thrift.PrependError(fmt.Sprintf("%T write field end error 4:avatarAuto: ", p), err) }
335 | return err
336 | }
337 |
338 | func (p *UserInfo) writeField5(oprot thrift.TProtocol) (err error) {
339 | if err := oprot.WriteFieldBegin("gold", thrift.I64, 5); err != nil {
340 | return thrift.PrependError(fmt.Sprintf("%T write field begin error 5:gold: ", p), err) }
341 | if err := oprot.WriteI64(int64(p.Gold)); err != nil {
342 | return thrift.PrependError(fmt.Sprintf("%T.gold (5) field write error: ", p), err) }
343 | if err := oprot.WriteFieldEnd(); err != nil {
344 | return thrift.PrependError(fmt.Sprintf("%T write field end error 5:gold: ", p), err) }
345 | return err
346 | }
347 |
348 | func (p *UserInfo) writeField6(oprot thrift.TProtocol) (err error) {
349 | if err := oprot.WriteFieldBegin("token", thrift.STRING, 6); err != nil {
350 | return thrift.PrependError(fmt.Sprintf("%T write field begin error 6:token: ", p), err) }
351 | if err := oprot.WriteString(string(p.Token)); err != nil {
352 | return thrift.PrependError(fmt.Sprintf("%T.token (6) field write error: ", p), err) }
353 | if err := oprot.WriteFieldEnd(); err != nil {
354 | return thrift.PrependError(fmt.Sprintf("%T write field end error 6:token: ", p), err) }
355 | return err
356 | }
357 |
358 | func (p *UserInfo) String() string {
359 | if p == nil {
360 | return ""
361 | }
362 | return fmt.Sprintf("UserInfo(%+v)", *p)
363 | }
364 |
365 | // Attributes:
366 | // - Code
367 | // - UserObj
368 | type Result_ struct {
369 | Code ErrorCode `thrift:"code,1" db:"code" json:"code"`
370 | UserObj *UserInfo `thrift:"user_obj,2" db:"user_obj" json:"user_obj"`
371 | }
372 |
373 | func NewResult_() *Result_ {
374 | return &Result_{}
375 | }
376 |
377 |
378 | func (p *Result_) GetCode() ErrorCode {
379 | return p.Code
380 | }
381 | var Result__UserObj_DEFAULT *UserInfo
382 | func (p *Result_) GetUserObj() *UserInfo {
383 | if !p.IsSetUserObj() {
384 | return Result__UserObj_DEFAULT
385 | }
386 | return p.UserObj
387 | }
388 | func (p *Result_) IsSetUserObj() bool {
389 | return p.UserObj != nil
390 | }
391 |
392 | func (p *Result_) Read(iprot thrift.TProtocol) error {
393 | if _, err := iprot.ReadStructBegin(); err != nil {
394 | return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
395 | }
396 |
397 |
398 | for {
399 | _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
400 | if err != nil {
401 | return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
402 | }
403 | if fieldTypeId == thrift.STOP { break; }
404 | switch fieldId {
405 | case 1:
406 | if fieldTypeId == thrift.I32 {
407 | if err := p.ReadField1(iprot); err != nil {
408 | return err
409 | }
410 | } else {
411 | if err := iprot.Skip(fieldTypeId); err != nil {
412 | return err
413 | }
414 | }
415 | case 2:
416 | if fieldTypeId == thrift.STRUCT {
417 | if err := p.ReadField2(iprot); err != nil {
418 | return err
419 | }
420 | } else {
421 | if err := iprot.Skip(fieldTypeId); err != nil {
422 | return err
423 | }
424 | }
425 | default:
426 | if err := iprot.Skip(fieldTypeId); err != nil {
427 | return err
428 | }
429 | }
430 | if err := iprot.ReadFieldEnd(); err != nil {
431 | return err
432 | }
433 | }
434 | if err := iprot.ReadStructEnd(); err != nil {
435 | return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
436 | }
437 | return nil
438 | }
439 |
440 | func (p *Result_) ReadField1(iprot thrift.TProtocol) error {
441 | if v, err := iprot.ReadI32(); err != nil {
442 | return thrift.PrependError("error reading field 1: ", err)
443 | } else {
444 | temp := ErrorCode(v)
445 | p.Code = temp
446 | }
447 | return nil
448 | }
449 |
450 | func (p *Result_) ReadField2(iprot thrift.TProtocol) error {
451 | p.UserObj = &UserInfo{}
452 | if err := p.UserObj.Read(iprot); err != nil {
453 | return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.UserObj), err)
454 | }
455 | return nil
456 | }
457 |
458 | func (p *Result_) Write(oprot thrift.TProtocol) error {
459 | if err := oprot.WriteStructBegin("Result"); err != nil {
460 | return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) }
461 | if p != nil {
462 | if err := p.writeField1(oprot); err != nil { return err }
463 | if err := p.writeField2(oprot); err != nil { return err }
464 | }
465 | if err := oprot.WriteFieldStop(); err != nil {
466 | return thrift.PrependError("write field stop error: ", err) }
467 | if err := oprot.WriteStructEnd(); err != nil {
468 | return thrift.PrependError("write struct stop error: ", err) }
469 | return nil
470 | }
471 |
472 | func (p *Result_) writeField1(oprot thrift.TProtocol) (err error) {
473 | if err := oprot.WriteFieldBegin("code", thrift.I32, 1); err != nil {
474 | return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:code: ", p), err) }
475 | if err := oprot.WriteI32(int32(p.Code)); err != nil {
476 | return thrift.PrependError(fmt.Sprintf("%T.code (1) field write error: ", p), err) }
477 | if err := oprot.WriteFieldEnd(); err != nil {
478 | return thrift.PrependError(fmt.Sprintf("%T write field end error 1:code: ", p), err) }
479 | return err
480 | }
481 |
482 | func (p *Result_) writeField2(oprot thrift.TProtocol) (err error) {
483 | if err := oprot.WriteFieldBegin("user_obj", thrift.STRUCT, 2); err != nil {
484 | return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:user_obj: ", p), err) }
485 | if err := p.UserObj.Write(oprot); err != nil {
486 | return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.UserObj), err)
487 | }
488 | if err := oprot.WriteFieldEnd(); err != nil {
489 | return thrift.PrependError(fmt.Sprintf("%T write field end error 2:user_obj: ", p), err) }
490 | return err
491 | }
492 |
493 | func (p *Result_) String() string {
494 | if p == nil {
495 | return ""
496 | }
497 | return fmt.Sprintf("Result_(%+v)", *p)
498 | }
499 |
500 | type UserService interface {
501 | // Parameters:
502 | // - NickName
503 | // - AvatarAuto
504 | // - Gold
505 | CreateNewUser(ctx context.Context, nickName string, avatarAuto string, gold int64) (r *Result_, err error)
506 | // Parameters:
507 | // - UserId
508 | GetUserInfoById(ctx context.Context, userId int32) (r *Result_, err error)
509 | // Parameters:
510 | // - Token
511 | GetUserInfoByken(ctx context.Context, token string) (r *Result_, err error)
512 | // Parameters:
513 | // - Behavior
514 | // - UserId
515 | // - Gold
516 | ModifyGoldById(ctx context.Context, behavior string, userId int32, gold int64) (r *Result_, err error)
517 | // Parameters:
518 | // - Behavior
519 | // - Token
520 | // - Gold
521 | ModifyGoldByToken(ctx context.Context, behavior string, token string, gold int64) (r *Result_, err error)
522 | }
523 |
524 | type UserServiceClient struct {
525 | c thrift.TClient
526 | }
527 |
528 | // Deprecated: Use NewUserService instead
529 | func NewUserServiceClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *UserServiceClient {
530 | return &UserServiceClient{
531 | c: thrift.NewTStandardClient(f.GetProtocol(t), f.GetProtocol(t)),
532 | }
533 | }
534 |
535 | // Deprecated: Use NewUserService instead
536 | func NewUserServiceClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *UserServiceClient {
537 | return &UserServiceClient{
538 | c: thrift.NewTStandardClient(iprot, oprot),
539 | }
540 | }
541 |
542 | func NewUserServiceClient(c thrift.TClient) *UserServiceClient {
543 | return &UserServiceClient{
544 | c: c,
545 | }
546 | }
547 |
548 | // Parameters:
549 | // - NickName
550 | // - AvatarAuto
551 | // - Gold
552 | func (p *UserServiceClient) CreateNewUser(ctx context.Context, nickName string, avatarAuto string, gold int64) (r *Result_, err error) {
553 | var _args0 UserServiceCreateNewUserArgs
554 | _args0.NickName = nickName
555 | _args0.AvatarAuto = avatarAuto
556 | _args0.Gold = gold
557 | var _result1 UserServiceCreateNewUserResult
558 | if err = p.c.Call(ctx, "createNewUser", &_args0, &_result1); err != nil {
559 | return
560 | }
561 | return _result1.GetSuccess(), nil
562 | }
563 |
564 | // Parameters:
565 | // - UserId
566 | func (p *UserServiceClient) GetUserInfoById(ctx context.Context, userId int32) (r *Result_, err error) {
567 | var _args2 UserServiceGetUserInfoByIdArgs
568 | _args2.UserId = userId
569 | var _result3 UserServiceGetUserInfoByIdResult
570 | if err = p.c.Call(ctx, "getUserInfoById", &_args2, &_result3); err != nil {
571 | return
572 | }
573 | return _result3.GetSuccess(), nil
574 | }
575 |
576 | // Parameters:
577 | // - Token
578 | func (p *UserServiceClient) GetUserInfoByken(ctx context.Context, token string) (r *Result_, err error) {
579 | var _args4 UserServiceGetUserInfoBykenArgs
580 | _args4.Token = token
581 | var _result5 UserServiceGetUserInfoBykenResult
582 | if err = p.c.Call(ctx, "getUserInfoByken", &_args4, &_result5); err != nil {
583 | return
584 | }
585 | return _result5.GetSuccess(), nil
586 | }
587 |
588 | // Parameters:
589 | // - Behavior
590 | // - UserId
591 | // - Gold
592 | func (p *UserServiceClient) ModifyGoldById(ctx context.Context, behavior string, userId int32, gold int64) (r *Result_, err error) {
593 | var _args6 UserServiceModifyGoldByIdArgs
594 | _args6.Behavior = behavior
595 | _args6.UserId = userId
596 | _args6.Gold = gold
597 | var _result7 UserServiceModifyGoldByIdResult
598 | if err = p.c.Call(ctx, "modifyGoldById", &_args6, &_result7); err != nil {
599 | return
600 | }
601 | return _result7.GetSuccess(), nil
602 | }
603 |
604 | // Parameters:
605 | // - Behavior
606 | // - Token
607 | // - Gold
608 | func (p *UserServiceClient) ModifyGoldByToken(ctx context.Context, behavior string, token string, gold int64) (r *Result_, err error) {
609 | var _args8 UserServiceModifyGoldByTokenArgs
610 | _args8.Behavior = behavior
611 | _args8.Token = token
612 | _args8.Gold = gold
613 | var _result9 UserServiceModifyGoldByTokenResult
614 | if err = p.c.Call(ctx, "modifyGoldByToken", &_args8, &_result9); err != nil {
615 | return
616 | }
617 | return _result9.GetSuccess(), nil
618 | }
619 |
620 | type UserServiceProcessor struct {
621 | processorMap map[string]thrift.TProcessorFunction
622 | handler UserService
623 | }
624 |
625 | func (p *UserServiceProcessor) AddToProcessorMap(key string, processor thrift.TProcessorFunction) {
626 | p.processorMap[key] = processor
627 | }
628 |
629 | func (p *UserServiceProcessor) GetProcessorFunction(key string) (processor thrift.TProcessorFunction, ok bool) {
630 | processor, ok = p.processorMap[key]
631 | return processor, ok
632 | }
633 |
634 | func (p *UserServiceProcessor) ProcessorMap() map[string]thrift.TProcessorFunction {
635 | return p.processorMap
636 | }
637 |
638 | func NewUserServiceProcessor(handler UserService) *UserServiceProcessor {
639 |
640 | self10 := &UserServiceProcessor{handler:handler, processorMap:make(map[string]thrift.TProcessorFunction)}
641 | self10.processorMap["createNewUser"] = &userServiceProcessorCreateNewUser{handler:handler}
642 | self10.processorMap["getUserInfoById"] = &userServiceProcessorGetUserInfoById{handler:handler}
643 | self10.processorMap["getUserInfoByken"] = &userServiceProcessorGetUserInfoByken{handler:handler}
644 | self10.processorMap["modifyGoldById"] = &userServiceProcessorModifyGoldById{handler:handler}
645 | self10.processorMap["modifyGoldByToken"] = &userServiceProcessorModifyGoldByToken{handler:handler}
646 | return self10
647 | }
648 |
649 | func (p *UserServiceProcessor) Process(ctx context.Context, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) {
650 | name, _, seqId, err := iprot.ReadMessageBegin()
651 | if err != nil { return false, err }
652 | if processor, ok := p.GetProcessorFunction(name); ok {
653 | return processor.Process(ctx, seqId, iprot, oprot)
654 | }
655 | iprot.Skip(thrift.STRUCT)
656 | iprot.ReadMessageEnd()
657 | x11 := thrift.NewTApplicationException(thrift.UNKNOWN_METHOD, "Unknown function " + name)
658 | oprot.WriteMessageBegin(name, thrift.EXCEPTION, seqId)
659 | x11.Write(oprot)
660 | oprot.WriteMessageEnd()
661 | oprot.Flush()
662 | return false, x11
663 |
664 | }
665 |
666 | type userServiceProcessorCreateNewUser struct {
667 | handler UserService
668 | }
669 |
670 | func (p *userServiceProcessorCreateNewUser) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) {
671 | args := UserServiceCreateNewUserArgs{}
672 | if err = args.Read(iprot); err != nil {
673 | iprot.ReadMessageEnd()
674 | x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error())
675 | oprot.WriteMessageBegin("createNewUser", thrift.EXCEPTION, seqId)
676 | x.Write(oprot)
677 | oprot.WriteMessageEnd()
678 | oprot.Flush()
679 | return false, err
680 | }
681 |
682 | iprot.ReadMessageEnd()
683 | result := UserServiceCreateNewUserResult{}
684 | var retval *Result_
685 | var err2 error
686 | if retval, err2 = p.handler.CreateNewUser(ctx, args.NickName, args.AvatarAuto, args.Gold); err2 != nil {
687 | x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing createNewUser: " + err2.Error())
688 | oprot.WriteMessageBegin("createNewUser", thrift.EXCEPTION, seqId)
689 | x.Write(oprot)
690 | oprot.WriteMessageEnd()
691 | oprot.Flush()
692 | return true, err2
693 | } else {
694 | result.Success = retval
695 | }
696 | if err2 = oprot.WriteMessageBegin("createNewUser", thrift.REPLY, seqId); err2 != nil {
697 | err = err2
698 | }
699 | if err2 = result.Write(oprot); err == nil && err2 != nil {
700 | err = err2
701 | }
702 | if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil {
703 | err = err2
704 | }
705 | if err2 = oprot.Flush(); err == nil && err2 != nil {
706 | err = err2
707 | }
708 | if err != nil {
709 | return
710 | }
711 | return true, err
712 | }
713 |
714 | type userServiceProcessorGetUserInfoById struct {
715 | handler UserService
716 | }
717 |
718 | func (p *userServiceProcessorGetUserInfoById) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) {
719 | args := UserServiceGetUserInfoByIdArgs{}
720 | if err = args.Read(iprot); err != nil {
721 | iprot.ReadMessageEnd()
722 | x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error())
723 | oprot.WriteMessageBegin("getUserInfoById", thrift.EXCEPTION, seqId)
724 | x.Write(oprot)
725 | oprot.WriteMessageEnd()
726 | oprot.Flush()
727 | return false, err
728 | }
729 |
730 | iprot.ReadMessageEnd()
731 | result := UserServiceGetUserInfoByIdResult{}
732 | var retval *Result_
733 | var err2 error
734 | if retval, err2 = p.handler.GetUserInfoById(ctx, args.UserId); err2 != nil {
735 | x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getUserInfoById: " + err2.Error())
736 | oprot.WriteMessageBegin("getUserInfoById", thrift.EXCEPTION, seqId)
737 | x.Write(oprot)
738 | oprot.WriteMessageEnd()
739 | oprot.Flush()
740 | return true, err2
741 | } else {
742 | result.Success = retval
743 | }
744 | if err2 = oprot.WriteMessageBegin("getUserInfoById", thrift.REPLY, seqId); err2 != nil {
745 | err = err2
746 | }
747 | if err2 = result.Write(oprot); err == nil && err2 != nil {
748 | err = err2
749 | }
750 | if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil {
751 | err = err2
752 | }
753 | if err2 = oprot.Flush(); err == nil && err2 != nil {
754 | err = err2
755 | }
756 | if err != nil {
757 | return
758 | }
759 | return true, err
760 | }
761 |
762 | type userServiceProcessorGetUserInfoByken struct {
763 | handler UserService
764 | }
765 |
766 | func (p *userServiceProcessorGetUserInfoByken) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) {
767 | args := UserServiceGetUserInfoBykenArgs{}
768 | if err = args.Read(iprot); err != nil {
769 | iprot.ReadMessageEnd()
770 | x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error())
771 | oprot.WriteMessageBegin("getUserInfoByken", thrift.EXCEPTION, seqId)
772 | x.Write(oprot)
773 | oprot.WriteMessageEnd()
774 | oprot.Flush()
775 | return false, err
776 | }
777 |
778 | iprot.ReadMessageEnd()
779 | result := UserServiceGetUserInfoBykenResult{}
780 | var retval *Result_
781 | var err2 error
782 | if retval, err2 = p.handler.GetUserInfoByken(ctx, args.Token); err2 != nil {
783 | x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing getUserInfoByken: " + err2.Error())
784 | oprot.WriteMessageBegin("getUserInfoByken", thrift.EXCEPTION, seqId)
785 | x.Write(oprot)
786 | oprot.WriteMessageEnd()
787 | oprot.Flush()
788 | return true, err2
789 | } else {
790 | result.Success = retval
791 | }
792 | if err2 = oprot.WriteMessageBegin("getUserInfoByken", thrift.REPLY, seqId); err2 != nil {
793 | err = err2
794 | }
795 | if err2 = result.Write(oprot); err == nil && err2 != nil {
796 | err = err2
797 | }
798 | if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil {
799 | err = err2
800 | }
801 | if err2 = oprot.Flush(); err == nil && err2 != nil {
802 | err = err2
803 | }
804 | if err != nil {
805 | return
806 | }
807 | return true, err
808 | }
809 |
810 | type userServiceProcessorModifyGoldById struct {
811 | handler UserService
812 | }
813 |
814 | func (p *userServiceProcessorModifyGoldById) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) {
815 | args := UserServiceModifyGoldByIdArgs{}
816 | if err = args.Read(iprot); err != nil {
817 | iprot.ReadMessageEnd()
818 | x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error())
819 | oprot.WriteMessageBegin("modifyGoldById", thrift.EXCEPTION, seqId)
820 | x.Write(oprot)
821 | oprot.WriteMessageEnd()
822 | oprot.Flush()
823 | return false, err
824 | }
825 |
826 | iprot.ReadMessageEnd()
827 | result := UserServiceModifyGoldByIdResult{}
828 | var retval *Result_
829 | var err2 error
830 | if retval, err2 = p.handler.ModifyGoldById(ctx, args.Behavior, args.UserId, args.Gold); err2 != nil {
831 | x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing modifyGoldById: " + err2.Error())
832 | oprot.WriteMessageBegin("modifyGoldById", thrift.EXCEPTION, seqId)
833 | x.Write(oprot)
834 | oprot.WriteMessageEnd()
835 | oprot.Flush()
836 | return true, err2
837 | } else {
838 | result.Success = retval
839 | }
840 | if err2 = oprot.WriteMessageBegin("modifyGoldById", thrift.REPLY, seqId); err2 != nil {
841 | err = err2
842 | }
843 | if err2 = result.Write(oprot); err == nil && err2 != nil {
844 | err = err2
845 | }
846 | if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil {
847 | err = err2
848 | }
849 | if err2 = oprot.Flush(); err == nil && err2 != nil {
850 | err = err2
851 | }
852 | if err != nil {
853 | return
854 | }
855 | return true, err
856 | }
857 |
858 | type userServiceProcessorModifyGoldByToken struct {
859 | handler UserService
860 | }
861 |
862 | func (p *userServiceProcessorModifyGoldByToken) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) {
863 | args := UserServiceModifyGoldByTokenArgs{}
864 | if err = args.Read(iprot); err != nil {
865 | iprot.ReadMessageEnd()
866 | x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error())
867 | oprot.WriteMessageBegin("modifyGoldByToken", thrift.EXCEPTION, seqId)
868 | x.Write(oprot)
869 | oprot.WriteMessageEnd()
870 | oprot.Flush()
871 | return false, err
872 | }
873 |
874 | iprot.ReadMessageEnd()
875 | result := UserServiceModifyGoldByTokenResult{}
876 | var retval *Result_
877 | var err2 error
878 | if retval, err2 = p.handler.ModifyGoldByToken(ctx, args.Behavior, args.Token, args.Gold); err2 != nil {
879 | x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing modifyGoldByToken: " + err2.Error())
880 | oprot.WriteMessageBegin("modifyGoldByToken", thrift.EXCEPTION, seqId)
881 | x.Write(oprot)
882 | oprot.WriteMessageEnd()
883 | oprot.Flush()
884 | return true, err2
885 | } else {
886 | result.Success = retval
887 | }
888 | if err2 = oprot.WriteMessageBegin("modifyGoldByToken", thrift.REPLY, seqId); err2 != nil {
889 | err = err2
890 | }
891 | if err2 = result.Write(oprot); err == nil && err2 != nil {
892 | err = err2
893 | }
894 | if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil {
895 | err = err2
896 | }
897 | if err2 = oprot.Flush(); err == nil && err2 != nil {
898 | err = err2
899 | }
900 | if err != nil {
901 | return
902 | }
903 | return true, err
904 | }
905 |
906 |
907 | // HELPER FUNCTIONS AND STRUCTURES
908 |
909 | // Attributes:
910 | // - NickName
911 | // - AvatarAuto
912 | // - Gold
913 | type UserServiceCreateNewUserArgs struct {
914 | NickName string `thrift:"nickName,1" db:"nickName" json:"nickName"`
915 | AvatarAuto string `thrift:"avatarAuto,2" db:"avatarAuto" json:"avatarAuto"`
916 | Gold int64 `thrift:"gold,3" db:"gold" json:"gold"`
917 | }
918 |
919 | func NewUserServiceCreateNewUserArgs() *UserServiceCreateNewUserArgs {
920 | return &UserServiceCreateNewUserArgs{}
921 | }
922 |
923 |
924 | func (p *UserServiceCreateNewUserArgs) GetNickName() string {
925 | return p.NickName
926 | }
927 |
928 | func (p *UserServiceCreateNewUserArgs) GetAvatarAuto() string {
929 | return p.AvatarAuto
930 | }
931 |
932 | func (p *UserServiceCreateNewUserArgs) GetGold() int64 {
933 | return p.Gold
934 | }
935 | func (p *UserServiceCreateNewUserArgs) Read(iprot thrift.TProtocol) error {
936 | if _, err := iprot.ReadStructBegin(); err != nil {
937 | return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
938 | }
939 |
940 |
941 | for {
942 | _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
943 | if err != nil {
944 | return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
945 | }
946 | if fieldTypeId == thrift.STOP { break; }
947 | switch fieldId {
948 | case 1:
949 | if fieldTypeId == thrift.STRING {
950 | if err := p.ReadField1(iprot); err != nil {
951 | return err
952 | }
953 | } else {
954 | if err := iprot.Skip(fieldTypeId); err != nil {
955 | return err
956 | }
957 | }
958 | case 2:
959 | if fieldTypeId == thrift.STRING {
960 | if err := p.ReadField2(iprot); err != nil {
961 | return err
962 | }
963 | } else {
964 | if err := iprot.Skip(fieldTypeId); err != nil {
965 | return err
966 | }
967 | }
968 | case 3:
969 | if fieldTypeId == thrift.I64 {
970 | if err := p.ReadField3(iprot); err != nil {
971 | return err
972 | }
973 | } else {
974 | if err := iprot.Skip(fieldTypeId); err != nil {
975 | return err
976 | }
977 | }
978 | default:
979 | if err := iprot.Skip(fieldTypeId); err != nil {
980 | return err
981 | }
982 | }
983 | if err := iprot.ReadFieldEnd(); err != nil {
984 | return err
985 | }
986 | }
987 | if err := iprot.ReadStructEnd(); err != nil {
988 | return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
989 | }
990 | return nil
991 | }
992 |
993 | func (p *UserServiceCreateNewUserArgs) ReadField1(iprot thrift.TProtocol) error {
994 | if v, err := iprot.ReadString(); err != nil {
995 | return thrift.PrependError("error reading field 1: ", err)
996 | } else {
997 | p.NickName = v
998 | }
999 | return nil
1000 | }
1001 |
1002 | func (p *UserServiceCreateNewUserArgs) ReadField2(iprot thrift.TProtocol) error {
1003 | if v, err := iprot.ReadString(); err != nil {
1004 | return thrift.PrependError("error reading field 2: ", err)
1005 | } else {
1006 | p.AvatarAuto = v
1007 | }
1008 | return nil
1009 | }
1010 |
1011 | func (p *UserServiceCreateNewUserArgs) ReadField3(iprot thrift.TProtocol) error {
1012 | if v, err := iprot.ReadI64(); err != nil {
1013 | return thrift.PrependError("error reading field 3: ", err)
1014 | } else {
1015 | p.Gold = v
1016 | }
1017 | return nil
1018 | }
1019 |
1020 | func (p *UserServiceCreateNewUserArgs) Write(oprot thrift.TProtocol) error {
1021 | if err := oprot.WriteStructBegin("createNewUser_args"); err != nil {
1022 | return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) }
1023 | if p != nil {
1024 | if err := p.writeField1(oprot); err != nil { return err }
1025 | if err := p.writeField2(oprot); err != nil { return err }
1026 | if err := p.writeField3(oprot); err != nil { return err }
1027 | }
1028 | if err := oprot.WriteFieldStop(); err != nil {
1029 | return thrift.PrependError("write field stop error: ", err) }
1030 | if err := oprot.WriteStructEnd(); err != nil {
1031 | return thrift.PrependError("write struct stop error: ", err) }
1032 | return nil
1033 | }
1034 |
1035 | func (p *UserServiceCreateNewUserArgs) writeField1(oprot thrift.TProtocol) (err error) {
1036 | if err := oprot.WriteFieldBegin("nickName", thrift.STRING, 1); err != nil {
1037 | return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:nickName: ", p), err) }
1038 | if err := oprot.WriteString(string(p.NickName)); err != nil {
1039 | return thrift.PrependError(fmt.Sprintf("%T.nickName (1) field write error: ", p), err) }
1040 | if err := oprot.WriteFieldEnd(); err != nil {
1041 | return thrift.PrependError(fmt.Sprintf("%T write field end error 1:nickName: ", p), err) }
1042 | return err
1043 | }
1044 |
1045 | func (p *UserServiceCreateNewUserArgs) writeField2(oprot thrift.TProtocol) (err error) {
1046 | if err := oprot.WriteFieldBegin("avatarAuto", thrift.STRING, 2); err != nil {
1047 | return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:avatarAuto: ", p), err) }
1048 | if err := oprot.WriteString(string(p.AvatarAuto)); err != nil {
1049 | return thrift.PrependError(fmt.Sprintf("%T.avatarAuto (2) field write error: ", p), err) }
1050 | if err := oprot.WriteFieldEnd(); err != nil {
1051 | return thrift.PrependError(fmt.Sprintf("%T write field end error 2:avatarAuto: ", p), err) }
1052 | return err
1053 | }
1054 |
1055 | func (p *UserServiceCreateNewUserArgs) writeField3(oprot thrift.TProtocol) (err error) {
1056 | if err := oprot.WriteFieldBegin("gold", thrift.I64, 3); err != nil {
1057 | return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:gold: ", p), err) }
1058 | if err := oprot.WriteI64(int64(p.Gold)); err != nil {
1059 | return thrift.PrependError(fmt.Sprintf("%T.gold (3) field write error: ", p), err) }
1060 | if err := oprot.WriteFieldEnd(); err != nil {
1061 | return thrift.PrependError(fmt.Sprintf("%T write field end error 3:gold: ", p), err) }
1062 | return err
1063 | }
1064 |
1065 | func (p *UserServiceCreateNewUserArgs) String() string {
1066 | if p == nil {
1067 | return ""
1068 | }
1069 | return fmt.Sprintf("UserServiceCreateNewUserArgs(%+v)", *p)
1070 | }
1071 |
1072 | // Attributes:
1073 | // - Success
1074 | type UserServiceCreateNewUserResult struct {
1075 | Success *Result_ `thrift:"success,0" db:"success" json:"success,omitempty"`
1076 | }
1077 |
1078 | func NewUserServiceCreateNewUserResult() *UserServiceCreateNewUserResult {
1079 | return &UserServiceCreateNewUserResult{}
1080 | }
1081 |
1082 | var UserServiceCreateNewUserResult_Success_DEFAULT *Result_
1083 | func (p *UserServiceCreateNewUserResult) GetSuccess() *Result_ {
1084 | if !p.IsSetSuccess() {
1085 | return UserServiceCreateNewUserResult_Success_DEFAULT
1086 | }
1087 | return p.Success
1088 | }
1089 | func (p *UserServiceCreateNewUserResult) IsSetSuccess() bool {
1090 | return p.Success != nil
1091 | }
1092 |
1093 | func (p *UserServiceCreateNewUserResult) Read(iprot thrift.TProtocol) error {
1094 | if _, err := iprot.ReadStructBegin(); err != nil {
1095 | return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
1096 | }
1097 |
1098 |
1099 | for {
1100 | _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
1101 | if err != nil {
1102 | return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
1103 | }
1104 | if fieldTypeId == thrift.STOP { break; }
1105 | switch fieldId {
1106 | case 0:
1107 | if fieldTypeId == thrift.STRUCT {
1108 | if err := p.ReadField0(iprot); err != nil {
1109 | return err
1110 | }
1111 | } else {
1112 | if err := iprot.Skip(fieldTypeId); err != nil {
1113 | return err
1114 | }
1115 | }
1116 | default:
1117 | if err := iprot.Skip(fieldTypeId); err != nil {
1118 | return err
1119 | }
1120 | }
1121 | if err := iprot.ReadFieldEnd(); err != nil {
1122 | return err
1123 | }
1124 | }
1125 | if err := iprot.ReadStructEnd(); err != nil {
1126 | return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
1127 | }
1128 | return nil
1129 | }
1130 |
1131 | func (p *UserServiceCreateNewUserResult) ReadField0(iprot thrift.TProtocol) error {
1132 | p.Success = &Result_{}
1133 | if err := p.Success.Read(iprot); err != nil {
1134 | return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err)
1135 | }
1136 | return nil
1137 | }
1138 |
1139 | func (p *UserServiceCreateNewUserResult) Write(oprot thrift.TProtocol) error {
1140 | if err := oprot.WriteStructBegin("createNewUser_result"); err != nil {
1141 | return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) }
1142 | if p != nil {
1143 | if err := p.writeField0(oprot); err != nil { return err }
1144 | }
1145 | if err := oprot.WriteFieldStop(); err != nil {
1146 | return thrift.PrependError("write field stop error: ", err) }
1147 | if err := oprot.WriteStructEnd(); err != nil {
1148 | return thrift.PrependError("write struct stop error: ", err) }
1149 | return nil
1150 | }
1151 |
1152 | func (p *UserServiceCreateNewUserResult) writeField0(oprot thrift.TProtocol) (err error) {
1153 | if p.IsSetSuccess() {
1154 | if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil {
1155 | return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) }
1156 | if err := p.Success.Write(oprot); err != nil {
1157 | return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err)
1158 | }
1159 | if err := oprot.WriteFieldEnd(); err != nil {
1160 | return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) }
1161 | }
1162 | return err
1163 | }
1164 |
1165 | func (p *UserServiceCreateNewUserResult) String() string {
1166 | if p == nil {
1167 | return ""
1168 | }
1169 | return fmt.Sprintf("UserServiceCreateNewUserResult(%+v)", *p)
1170 | }
1171 |
1172 | // Attributes:
1173 | // - UserId
1174 | type UserServiceGetUserInfoByIdArgs struct {
1175 | UserId int32 `thrift:"userId,1" db:"userId" json:"userId"`
1176 | }
1177 |
1178 | func NewUserServiceGetUserInfoByIdArgs() *UserServiceGetUserInfoByIdArgs {
1179 | return &UserServiceGetUserInfoByIdArgs{}
1180 | }
1181 |
1182 |
1183 | func (p *UserServiceGetUserInfoByIdArgs) GetUserId() int32 {
1184 | return p.UserId
1185 | }
1186 | func (p *UserServiceGetUserInfoByIdArgs) Read(iprot thrift.TProtocol) error {
1187 | if _, err := iprot.ReadStructBegin(); err != nil {
1188 | return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
1189 | }
1190 |
1191 |
1192 | for {
1193 | _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
1194 | if err != nil {
1195 | return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
1196 | }
1197 | if fieldTypeId == thrift.STOP { break; }
1198 | switch fieldId {
1199 | case 1:
1200 | if fieldTypeId == thrift.I32 {
1201 | if err := p.ReadField1(iprot); err != nil {
1202 | return err
1203 | }
1204 | } else {
1205 | if err := iprot.Skip(fieldTypeId); err != nil {
1206 | return err
1207 | }
1208 | }
1209 | default:
1210 | if err := iprot.Skip(fieldTypeId); err != nil {
1211 | return err
1212 | }
1213 | }
1214 | if err := iprot.ReadFieldEnd(); err != nil {
1215 | return err
1216 | }
1217 | }
1218 | if err := iprot.ReadStructEnd(); err != nil {
1219 | return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
1220 | }
1221 | return nil
1222 | }
1223 |
1224 | func (p *UserServiceGetUserInfoByIdArgs) ReadField1(iprot thrift.TProtocol) error {
1225 | if v, err := iprot.ReadI32(); err != nil {
1226 | return thrift.PrependError("error reading field 1: ", err)
1227 | } else {
1228 | p.UserId = v
1229 | }
1230 | return nil
1231 | }
1232 |
1233 | func (p *UserServiceGetUserInfoByIdArgs) Write(oprot thrift.TProtocol) error {
1234 | if err := oprot.WriteStructBegin("getUserInfoById_args"); err != nil {
1235 | return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) }
1236 | if p != nil {
1237 | if err := p.writeField1(oprot); err != nil { return err }
1238 | }
1239 | if err := oprot.WriteFieldStop(); err != nil {
1240 | return thrift.PrependError("write field stop error: ", err) }
1241 | if err := oprot.WriteStructEnd(); err != nil {
1242 | return thrift.PrependError("write struct stop error: ", err) }
1243 | return nil
1244 | }
1245 |
1246 | func (p *UserServiceGetUserInfoByIdArgs) writeField1(oprot thrift.TProtocol) (err error) {
1247 | if err := oprot.WriteFieldBegin("userId", thrift.I32, 1); err != nil {
1248 | return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:userId: ", p), err) }
1249 | if err := oprot.WriteI32(int32(p.UserId)); err != nil {
1250 | return thrift.PrependError(fmt.Sprintf("%T.userId (1) field write error: ", p), err) }
1251 | if err := oprot.WriteFieldEnd(); err != nil {
1252 | return thrift.PrependError(fmt.Sprintf("%T write field end error 1:userId: ", p), err) }
1253 | return err
1254 | }
1255 |
1256 | func (p *UserServiceGetUserInfoByIdArgs) String() string {
1257 | if p == nil {
1258 | return ""
1259 | }
1260 | return fmt.Sprintf("UserServiceGetUserInfoByIdArgs(%+v)", *p)
1261 | }
1262 |
1263 | // Attributes:
1264 | // - Success
1265 | type UserServiceGetUserInfoByIdResult struct {
1266 | Success *Result_ `thrift:"success,0" db:"success" json:"success,omitempty"`
1267 | }
1268 |
1269 | func NewUserServiceGetUserInfoByIdResult() *UserServiceGetUserInfoByIdResult {
1270 | return &UserServiceGetUserInfoByIdResult{}
1271 | }
1272 |
1273 | var UserServiceGetUserInfoByIdResult_Success_DEFAULT *Result_
1274 | func (p *UserServiceGetUserInfoByIdResult) GetSuccess() *Result_ {
1275 | if !p.IsSetSuccess() {
1276 | return UserServiceGetUserInfoByIdResult_Success_DEFAULT
1277 | }
1278 | return p.Success
1279 | }
1280 | func (p *UserServiceGetUserInfoByIdResult) IsSetSuccess() bool {
1281 | return p.Success != nil
1282 | }
1283 |
1284 | func (p *UserServiceGetUserInfoByIdResult) Read(iprot thrift.TProtocol) error {
1285 | if _, err := iprot.ReadStructBegin(); err != nil {
1286 | return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
1287 | }
1288 |
1289 |
1290 | for {
1291 | _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
1292 | if err != nil {
1293 | return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
1294 | }
1295 | if fieldTypeId == thrift.STOP { break; }
1296 | switch fieldId {
1297 | case 0:
1298 | if fieldTypeId == thrift.STRUCT {
1299 | if err := p.ReadField0(iprot); err != nil {
1300 | return err
1301 | }
1302 | } else {
1303 | if err := iprot.Skip(fieldTypeId); err != nil {
1304 | return err
1305 | }
1306 | }
1307 | default:
1308 | if err := iprot.Skip(fieldTypeId); err != nil {
1309 | return err
1310 | }
1311 | }
1312 | if err := iprot.ReadFieldEnd(); err != nil {
1313 | return err
1314 | }
1315 | }
1316 | if err := iprot.ReadStructEnd(); err != nil {
1317 | return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
1318 | }
1319 | return nil
1320 | }
1321 |
1322 | func (p *UserServiceGetUserInfoByIdResult) ReadField0(iprot thrift.TProtocol) error {
1323 | p.Success = &Result_{}
1324 | if err := p.Success.Read(iprot); err != nil {
1325 | return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err)
1326 | }
1327 | return nil
1328 | }
1329 |
1330 | func (p *UserServiceGetUserInfoByIdResult) Write(oprot thrift.TProtocol) error {
1331 | if err := oprot.WriteStructBegin("getUserInfoById_result"); err != nil {
1332 | return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) }
1333 | if p != nil {
1334 | if err := p.writeField0(oprot); err != nil { return err }
1335 | }
1336 | if err := oprot.WriteFieldStop(); err != nil {
1337 | return thrift.PrependError("write field stop error: ", err) }
1338 | if err := oprot.WriteStructEnd(); err != nil {
1339 | return thrift.PrependError("write struct stop error: ", err) }
1340 | return nil
1341 | }
1342 |
1343 | func (p *UserServiceGetUserInfoByIdResult) writeField0(oprot thrift.TProtocol) (err error) {
1344 | if p.IsSetSuccess() {
1345 | if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil {
1346 | return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) }
1347 | if err := p.Success.Write(oprot); err != nil {
1348 | return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err)
1349 | }
1350 | if err := oprot.WriteFieldEnd(); err != nil {
1351 | return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) }
1352 | }
1353 | return err
1354 | }
1355 |
1356 | func (p *UserServiceGetUserInfoByIdResult) String() string {
1357 | if p == nil {
1358 | return ""
1359 | }
1360 | return fmt.Sprintf("UserServiceGetUserInfoByIdResult(%+v)", *p)
1361 | }
1362 |
1363 | // Attributes:
1364 | // - Token
1365 | type UserServiceGetUserInfoBykenArgs struct {
1366 | Token string `thrift:"token,1" db:"token" json:"token"`
1367 | }
1368 |
1369 | func NewUserServiceGetUserInfoBykenArgs() *UserServiceGetUserInfoBykenArgs {
1370 | return &UserServiceGetUserInfoBykenArgs{}
1371 | }
1372 |
1373 |
1374 | func (p *UserServiceGetUserInfoBykenArgs) GetToken() string {
1375 | return p.Token
1376 | }
1377 | func (p *UserServiceGetUserInfoBykenArgs) Read(iprot thrift.TProtocol) error {
1378 | if _, err := iprot.ReadStructBegin(); err != nil {
1379 | return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
1380 | }
1381 |
1382 |
1383 | for {
1384 | _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
1385 | if err != nil {
1386 | return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
1387 | }
1388 | if fieldTypeId == thrift.STOP { break; }
1389 | switch fieldId {
1390 | case 1:
1391 | if fieldTypeId == thrift.STRING {
1392 | if err := p.ReadField1(iprot); err != nil {
1393 | return err
1394 | }
1395 | } else {
1396 | if err := iprot.Skip(fieldTypeId); err != nil {
1397 | return err
1398 | }
1399 | }
1400 | default:
1401 | if err := iprot.Skip(fieldTypeId); err != nil {
1402 | return err
1403 | }
1404 | }
1405 | if err := iprot.ReadFieldEnd(); err != nil {
1406 | return err
1407 | }
1408 | }
1409 | if err := iprot.ReadStructEnd(); err != nil {
1410 | return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
1411 | }
1412 | return nil
1413 | }
1414 |
1415 | func (p *UserServiceGetUserInfoBykenArgs) ReadField1(iprot thrift.TProtocol) error {
1416 | if v, err := iprot.ReadString(); err != nil {
1417 | return thrift.PrependError("error reading field 1: ", err)
1418 | } else {
1419 | p.Token = v
1420 | }
1421 | return nil
1422 | }
1423 |
1424 | func (p *UserServiceGetUserInfoBykenArgs) Write(oprot thrift.TProtocol) error {
1425 | if err := oprot.WriteStructBegin("getUserInfoByken_args"); err != nil {
1426 | return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) }
1427 | if p != nil {
1428 | if err := p.writeField1(oprot); err != nil { return err }
1429 | }
1430 | if err := oprot.WriteFieldStop(); err != nil {
1431 | return thrift.PrependError("write field stop error: ", err) }
1432 | if err := oprot.WriteStructEnd(); err != nil {
1433 | return thrift.PrependError("write struct stop error: ", err) }
1434 | return nil
1435 | }
1436 |
1437 | func (p *UserServiceGetUserInfoBykenArgs) writeField1(oprot thrift.TProtocol) (err error) {
1438 | if err := oprot.WriteFieldBegin("token", thrift.STRING, 1); err != nil {
1439 | return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:token: ", p), err) }
1440 | if err := oprot.WriteString(string(p.Token)); err != nil {
1441 | return thrift.PrependError(fmt.Sprintf("%T.token (1) field write error: ", p), err) }
1442 | if err := oprot.WriteFieldEnd(); err != nil {
1443 | return thrift.PrependError(fmt.Sprintf("%T write field end error 1:token: ", p), err) }
1444 | return err
1445 | }
1446 |
1447 | func (p *UserServiceGetUserInfoBykenArgs) String() string {
1448 | if p == nil {
1449 | return ""
1450 | }
1451 | return fmt.Sprintf("UserServiceGetUserInfoBykenArgs(%+v)", *p)
1452 | }
1453 |
1454 | // Attributes:
1455 | // - Success
1456 | type UserServiceGetUserInfoBykenResult struct {
1457 | Success *Result_ `thrift:"success,0" db:"success" json:"success,omitempty"`
1458 | }
1459 |
1460 | func NewUserServiceGetUserInfoBykenResult() *UserServiceGetUserInfoBykenResult {
1461 | return &UserServiceGetUserInfoBykenResult{}
1462 | }
1463 |
1464 | var UserServiceGetUserInfoBykenResult_Success_DEFAULT *Result_
1465 | func (p *UserServiceGetUserInfoBykenResult) GetSuccess() *Result_ {
1466 | if !p.IsSetSuccess() {
1467 | return UserServiceGetUserInfoBykenResult_Success_DEFAULT
1468 | }
1469 | return p.Success
1470 | }
1471 | func (p *UserServiceGetUserInfoBykenResult) IsSetSuccess() bool {
1472 | return p.Success != nil
1473 | }
1474 |
1475 | func (p *UserServiceGetUserInfoBykenResult) Read(iprot thrift.TProtocol) error {
1476 | if _, err := iprot.ReadStructBegin(); err != nil {
1477 | return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
1478 | }
1479 |
1480 |
1481 | for {
1482 | _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
1483 | if err != nil {
1484 | return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
1485 | }
1486 | if fieldTypeId == thrift.STOP { break; }
1487 | switch fieldId {
1488 | case 0:
1489 | if fieldTypeId == thrift.STRUCT {
1490 | if err := p.ReadField0(iprot); err != nil {
1491 | return err
1492 | }
1493 | } else {
1494 | if err := iprot.Skip(fieldTypeId); err != nil {
1495 | return err
1496 | }
1497 | }
1498 | default:
1499 | if err := iprot.Skip(fieldTypeId); err != nil {
1500 | return err
1501 | }
1502 | }
1503 | if err := iprot.ReadFieldEnd(); err != nil {
1504 | return err
1505 | }
1506 | }
1507 | if err := iprot.ReadStructEnd(); err != nil {
1508 | return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
1509 | }
1510 | return nil
1511 | }
1512 |
1513 | func (p *UserServiceGetUserInfoBykenResult) ReadField0(iprot thrift.TProtocol) error {
1514 | p.Success = &Result_{}
1515 | if err := p.Success.Read(iprot); err != nil {
1516 | return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err)
1517 | }
1518 | return nil
1519 | }
1520 |
1521 | func (p *UserServiceGetUserInfoBykenResult) Write(oprot thrift.TProtocol) error {
1522 | if err := oprot.WriteStructBegin("getUserInfoByken_result"); err != nil {
1523 | return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) }
1524 | if p != nil {
1525 | if err := p.writeField0(oprot); err != nil { return err }
1526 | }
1527 | if err := oprot.WriteFieldStop(); err != nil {
1528 | return thrift.PrependError("write field stop error: ", err) }
1529 | if err := oprot.WriteStructEnd(); err != nil {
1530 | return thrift.PrependError("write struct stop error: ", err) }
1531 | return nil
1532 | }
1533 |
1534 | func (p *UserServiceGetUserInfoBykenResult) writeField0(oprot thrift.TProtocol) (err error) {
1535 | if p.IsSetSuccess() {
1536 | if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil {
1537 | return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) }
1538 | if err := p.Success.Write(oprot); err != nil {
1539 | return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err)
1540 | }
1541 | if err := oprot.WriteFieldEnd(); err != nil {
1542 | return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) }
1543 | }
1544 | return err
1545 | }
1546 |
1547 | func (p *UserServiceGetUserInfoBykenResult) String() string {
1548 | if p == nil {
1549 | return ""
1550 | }
1551 | return fmt.Sprintf("UserServiceGetUserInfoBykenResult(%+v)", *p)
1552 | }
1553 |
1554 | // Attributes:
1555 | // - Behavior
1556 | // - UserId
1557 | // - Gold
1558 | type UserServiceModifyGoldByIdArgs struct {
1559 | Behavior string `thrift:"behavior,1" db:"behavior" json:"behavior"`
1560 | UserId int32 `thrift:"userId,2" db:"userId" json:"userId"`
1561 | Gold int64 `thrift:"gold,3" db:"gold" json:"gold"`
1562 | }
1563 |
1564 | func NewUserServiceModifyGoldByIdArgs() *UserServiceModifyGoldByIdArgs {
1565 | return &UserServiceModifyGoldByIdArgs{}
1566 | }
1567 |
1568 |
1569 | func (p *UserServiceModifyGoldByIdArgs) GetBehavior() string {
1570 | return p.Behavior
1571 | }
1572 |
1573 | func (p *UserServiceModifyGoldByIdArgs) GetUserId() int32 {
1574 | return p.UserId
1575 | }
1576 |
1577 | func (p *UserServiceModifyGoldByIdArgs) GetGold() int64 {
1578 | return p.Gold
1579 | }
1580 | func (p *UserServiceModifyGoldByIdArgs) Read(iprot thrift.TProtocol) error {
1581 | if _, err := iprot.ReadStructBegin(); err != nil {
1582 | return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
1583 | }
1584 |
1585 |
1586 | for {
1587 | _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
1588 | if err != nil {
1589 | return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
1590 | }
1591 | if fieldTypeId == thrift.STOP { break; }
1592 | switch fieldId {
1593 | case 1:
1594 | if fieldTypeId == thrift.STRING {
1595 | if err := p.ReadField1(iprot); err != nil {
1596 | return err
1597 | }
1598 | } else {
1599 | if err := iprot.Skip(fieldTypeId); err != nil {
1600 | return err
1601 | }
1602 | }
1603 | case 2:
1604 | if fieldTypeId == thrift.I32 {
1605 | if err := p.ReadField2(iprot); err != nil {
1606 | return err
1607 | }
1608 | } else {
1609 | if err := iprot.Skip(fieldTypeId); err != nil {
1610 | return err
1611 | }
1612 | }
1613 | case 3:
1614 | if fieldTypeId == thrift.I64 {
1615 | if err := p.ReadField3(iprot); err != nil {
1616 | return err
1617 | }
1618 | } else {
1619 | if err := iprot.Skip(fieldTypeId); err != nil {
1620 | return err
1621 | }
1622 | }
1623 | default:
1624 | if err := iprot.Skip(fieldTypeId); err != nil {
1625 | return err
1626 | }
1627 | }
1628 | if err := iprot.ReadFieldEnd(); err != nil {
1629 | return err
1630 | }
1631 | }
1632 | if err := iprot.ReadStructEnd(); err != nil {
1633 | return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
1634 | }
1635 | return nil
1636 | }
1637 |
1638 | func (p *UserServiceModifyGoldByIdArgs) ReadField1(iprot thrift.TProtocol) error {
1639 | if v, err := iprot.ReadString(); err != nil {
1640 | return thrift.PrependError("error reading field 1: ", err)
1641 | } else {
1642 | p.Behavior = v
1643 | }
1644 | return nil
1645 | }
1646 |
1647 | func (p *UserServiceModifyGoldByIdArgs) ReadField2(iprot thrift.TProtocol) error {
1648 | if v, err := iprot.ReadI32(); err != nil {
1649 | return thrift.PrependError("error reading field 2: ", err)
1650 | } else {
1651 | p.UserId = v
1652 | }
1653 | return nil
1654 | }
1655 |
1656 | func (p *UserServiceModifyGoldByIdArgs) ReadField3(iprot thrift.TProtocol) error {
1657 | if v, err := iprot.ReadI64(); err != nil {
1658 | return thrift.PrependError("error reading field 3: ", err)
1659 | } else {
1660 | p.Gold = v
1661 | }
1662 | return nil
1663 | }
1664 |
1665 | func (p *UserServiceModifyGoldByIdArgs) Write(oprot thrift.TProtocol) error {
1666 | if err := oprot.WriteStructBegin("modifyGoldById_args"); err != nil {
1667 | return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) }
1668 | if p != nil {
1669 | if err := p.writeField1(oprot); err != nil { return err }
1670 | if err := p.writeField2(oprot); err != nil { return err }
1671 | if err := p.writeField3(oprot); err != nil { return err }
1672 | }
1673 | if err := oprot.WriteFieldStop(); err != nil {
1674 | return thrift.PrependError("write field stop error: ", err) }
1675 | if err := oprot.WriteStructEnd(); err != nil {
1676 | return thrift.PrependError("write struct stop error: ", err) }
1677 | return nil
1678 | }
1679 |
1680 | func (p *UserServiceModifyGoldByIdArgs) writeField1(oprot thrift.TProtocol) (err error) {
1681 | if err := oprot.WriteFieldBegin("behavior", thrift.STRING, 1); err != nil {
1682 | return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:behavior: ", p), err) }
1683 | if err := oprot.WriteString(string(p.Behavior)); err != nil {
1684 | return thrift.PrependError(fmt.Sprintf("%T.behavior (1) field write error: ", p), err) }
1685 | if err := oprot.WriteFieldEnd(); err != nil {
1686 | return thrift.PrependError(fmt.Sprintf("%T write field end error 1:behavior: ", p), err) }
1687 | return err
1688 | }
1689 |
1690 | func (p *UserServiceModifyGoldByIdArgs) writeField2(oprot thrift.TProtocol) (err error) {
1691 | if err := oprot.WriteFieldBegin("userId", thrift.I32, 2); err != nil {
1692 | return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:userId: ", p), err) }
1693 | if err := oprot.WriteI32(int32(p.UserId)); err != nil {
1694 | return thrift.PrependError(fmt.Sprintf("%T.userId (2) field write error: ", p), err) }
1695 | if err := oprot.WriteFieldEnd(); err != nil {
1696 | return thrift.PrependError(fmt.Sprintf("%T write field end error 2:userId: ", p), err) }
1697 | return err
1698 | }
1699 |
1700 | func (p *UserServiceModifyGoldByIdArgs) writeField3(oprot thrift.TProtocol) (err error) {
1701 | if err := oprot.WriteFieldBegin("gold", thrift.I64, 3); err != nil {
1702 | return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:gold: ", p), err) }
1703 | if err := oprot.WriteI64(int64(p.Gold)); err != nil {
1704 | return thrift.PrependError(fmt.Sprintf("%T.gold (3) field write error: ", p), err) }
1705 | if err := oprot.WriteFieldEnd(); err != nil {
1706 | return thrift.PrependError(fmt.Sprintf("%T write field end error 3:gold: ", p), err) }
1707 | return err
1708 | }
1709 |
1710 | func (p *UserServiceModifyGoldByIdArgs) String() string {
1711 | if p == nil {
1712 | return ""
1713 | }
1714 | return fmt.Sprintf("UserServiceModifyGoldByIdArgs(%+v)", *p)
1715 | }
1716 |
1717 | // Attributes:
1718 | // - Success
1719 | type UserServiceModifyGoldByIdResult struct {
1720 | Success *Result_ `thrift:"success,0" db:"success" json:"success,omitempty"`
1721 | }
1722 |
1723 | func NewUserServiceModifyGoldByIdResult() *UserServiceModifyGoldByIdResult {
1724 | return &UserServiceModifyGoldByIdResult{}
1725 | }
1726 |
1727 | var UserServiceModifyGoldByIdResult_Success_DEFAULT *Result_
1728 | func (p *UserServiceModifyGoldByIdResult) GetSuccess() *Result_ {
1729 | if !p.IsSetSuccess() {
1730 | return UserServiceModifyGoldByIdResult_Success_DEFAULT
1731 | }
1732 | return p.Success
1733 | }
1734 | func (p *UserServiceModifyGoldByIdResult) IsSetSuccess() bool {
1735 | return p.Success != nil
1736 | }
1737 |
1738 | func (p *UserServiceModifyGoldByIdResult) Read(iprot thrift.TProtocol) error {
1739 | if _, err := iprot.ReadStructBegin(); err != nil {
1740 | return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
1741 | }
1742 |
1743 |
1744 | for {
1745 | _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
1746 | if err != nil {
1747 | return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
1748 | }
1749 | if fieldTypeId == thrift.STOP { break; }
1750 | switch fieldId {
1751 | case 0:
1752 | if fieldTypeId == thrift.STRUCT {
1753 | if err := p.ReadField0(iprot); err != nil {
1754 | return err
1755 | }
1756 | } else {
1757 | if err := iprot.Skip(fieldTypeId); err != nil {
1758 | return err
1759 | }
1760 | }
1761 | default:
1762 | if err := iprot.Skip(fieldTypeId); err != nil {
1763 | return err
1764 | }
1765 | }
1766 | if err := iprot.ReadFieldEnd(); err != nil {
1767 | return err
1768 | }
1769 | }
1770 | if err := iprot.ReadStructEnd(); err != nil {
1771 | return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
1772 | }
1773 | return nil
1774 | }
1775 |
1776 | func (p *UserServiceModifyGoldByIdResult) ReadField0(iprot thrift.TProtocol) error {
1777 | p.Success = &Result_{}
1778 | if err := p.Success.Read(iprot); err != nil {
1779 | return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err)
1780 | }
1781 | return nil
1782 | }
1783 |
1784 | func (p *UserServiceModifyGoldByIdResult) Write(oprot thrift.TProtocol) error {
1785 | if err := oprot.WriteStructBegin("modifyGoldById_result"); err != nil {
1786 | return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) }
1787 | if p != nil {
1788 | if err := p.writeField0(oprot); err != nil { return err }
1789 | }
1790 | if err := oprot.WriteFieldStop(); err != nil {
1791 | return thrift.PrependError("write field stop error: ", err) }
1792 | if err := oprot.WriteStructEnd(); err != nil {
1793 | return thrift.PrependError("write struct stop error: ", err) }
1794 | return nil
1795 | }
1796 |
1797 | func (p *UserServiceModifyGoldByIdResult) writeField0(oprot thrift.TProtocol) (err error) {
1798 | if p.IsSetSuccess() {
1799 | if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil {
1800 | return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) }
1801 | if err := p.Success.Write(oprot); err != nil {
1802 | return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err)
1803 | }
1804 | if err := oprot.WriteFieldEnd(); err != nil {
1805 | return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) }
1806 | }
1807 | return err
1808 | }
1809 |
1810 | func (p *UserServiceModifyGoldByIdResult) String() string {
1811 | if p == nil {
1812 | return ""
1813 | }
1814 | return fmt.Sprintf("UserServiceModifyGoldByIdResult(%+v)", *p)
1815 | }
1816 |
1817 | // Attributes:
1818 | // - Behavior
1819 | // - Token
1820 | // - Gold
1821 | type UserServiceModifyGoldByTokenArgs struct {
1822 | Behavior string `thrift:"behavior,1" db:"behavior" json:"behavior"`
1823 | Token string `thrift:"token,2" db:"token" json:"token"`
1824 | Gold int64 `thrift:"gold,3" db:"gold" json:"gold"`
1825 | }
1826 |
1827 | func NewUserServiceModifyGoldByTokenArgs() *UserServiceModifyGoldByTokenArgs {
1828 | return &UserServiceModifyGoldByTokenArgs{}
1829 | }
1830 |
1831 |
1832 | func (p *UserServiceModifyGoldByTokenArgs) GetBehavior() string {
1833 | return p.Behavior
1834 | }
1835 |
1836 | func (p *UserServiceModifyGoldByTokenArgs) GetToken() string {
1837 | return p.Token
1838 | }
1839 |
1840 | func (p *UserServiceModifyGoldByTokenArgs) GetGold() int64 {
1841 | return p.Gold
1842 | }
1843 | func (p *UserServiceModifyGoldByTokenArgs) Read(iprot thrift.TProtocol) error {
1844 | if _, err := iprot.ReadStructBegin(); err != nil {
1845 | return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
1846 | }
1847 |
1848 |
1849 | for {
1850 | _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
1851 | if err != nil {
1852 | return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
1853 | }
1854 | if fieldTypeId == thrift.STOP { break; }
1855 | switch fieldId {
1856 | case 1:
1857 | if fieldTypeId == thrift.STRING {
1858 | if err := p.ReadField1(iprot); err != nil {
1859 | return err
1860 | }
1861 | } else {
1862 | if err := iprot.Skip(fieldTypeId); err != nil {
1863 | return err
1864 | }
1865 | }
1866 | case 2:
1867 | if fieldTypeId == thrift.STRING {
1868 | if err := p.ReadField2(iprot); err != nil {
1869 | return err
1870 | }
1871 | } else {
1872 | if err := iprot.Skip(fieldTypeId); err != nil {
1873 | return err
1874 | }
1875 | }
1876 | case 3:
1877 | if fieldTypeId == thrift.I64 {
1878 | if err := p.ReadField3(iprot); err != nil {
1879 | return err
1880 | }
1881 | } else {
1882 | if err := iprot.Skip(fieldTypeId); err != nil {
1883 | return err
1884 | }
1885 | }
1886 | default:
1887 | if err := iprot.Skip(fieldTypeId); err != nil {
1888 | return err
1889 | }
1890 | }
1891 | if err := iprot.ReadFieldEnd(); err != nil {
1892 | return err
1893 | }
1894 | }
1895 | if err := iprot.ReadStructEnd(); err != nil {
1896 | return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
1897 | }
1898 | return nil
1899 | }
1900 |
1901 | func (p *UserServiceModifyGoldByTokenArgs) ReadField1(iprot thrift.TProtocol) error {
1902 | if v, err := iprot.ReadString(); err != nil {
1903 | return thrift.PrependError("error reading field 1: ", err)
1904 | } else {
1905 | p.Behavior = v
1906 | }
1907 | return nil
1908 | }
1909 |
1910 | func (p *UserServiceModifyGoldByTokenArgs) ReadField2(iprot thrift.TProtocol) error {
1911 | if v, err := iprot.ReadString(); err != nil {
1912 | return thrift.PrependError("error reading field 2: ", err)
1913 | } else {
1914 | p.Token = v
1915 | }
1916 | return nil
1917 | }
1918 |
1919 | func (p *UserServiceModifyGoldByTokenArgs) ReadField3(iprot thrift.TProtocol) error {
1920 | if v, err := iprot.ReadI64(); err != nil {
1921 | return thrift.PrependError("error reading field 3: ", err)
1922 | } else {
1923 | p.Gold = v
1924 | }
1925 | return nil
1926 | }
1927 |
1928 | func (p *UserServiceModifyGoldByTokenArgs) Write(oprot thrift.TProtocol) error {
1929 | if err := oprot.WriteStructBegin("modifyGoldByToken_args"); err != nil {
1930 | return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) }
1931 | if p != nil {
1932 | if err := p.writeField1(oprot); err != nil { return err }
1933 | if err := p.writeField2(oprot); err != nil { return err }
1934 | if err := p.writeField3(oprot); err != nil { return err }
1935 | }
1936 | if err := oprot.WriteFieldStop(); err != nil {
1937 | return thrift.PrependError("write field stop error: ", err) }
1938 | if err := oprot.WriteStructEnd(); err != nil {
1939 | return thrift.PrependError("write struct stop error: ", err) }
1940 | return nil
1941 | }
1942 |
1943 | func (p *UserServiceModifyGoldByTokenArgs) writeField1(oprot thrift.TProtocol) (err error) {
1944 | if err := oprot.WriteFieldBegin("behavior", thrift.STRING, 1); err != nil {
1945 | return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:behavior: ", p), err) }
1946 | if err := oprot.WriteString(string(p.Behavior)); err != nil {
1947 | return thrift.PrependError(fmt.Sprintf("%T.behavior (1) field write error: ", p), err) }
1948 | if err := oprot.WriteFieldEnd(); err != nil {
1949 | return thrift.PrependError(fmt.Sprintf("%T write field end error 1:behavior: ", p), err) }
1950 | return err
1951 | }
1952 |
1953 | func (p *UserServiceModifyGoldByTokenArgs) writeField2(oprot thrift.TProtocol) (err error) {
1954 | if err := oprot.WriteFieldBegin("token", thrift.STRING, 2); err != nil {
1955 | return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:token: ", p), err) }
1956 | if err := oprot.WriteString(string(p.Token)); err != nil {
1957 | return thrift.PrependError(fmt.Sprintf("%T.token (2) field write error: ", p), err) }
1958 | if err := oprot.WriteFieldEnd(); err != nil {
1959 | return thrift.PrependError(fmt.Sprintf("%T write field end error 2:token: ", p), err) }
1960 | return err
1961 | }
1962 |
1963 | func (p *UserServiceModifyGoldByTokenArgs) writeField3(oprot thrift.TProtocol) (err error) {
1964 | if err := oprot.WriteFieldBegin("gold", thrift.I64, 3); err != nil {
1965 | return thrift.PrependError(fmt.Sprintf("%T write field begin error 3:gold: ", p), err) }
1966 | if err := oprot.WriteI64(int64(p.Gold)); err != nil {
1967 | return thrift.PrependError(fmt.Sprintf("%T.gold (3) field write error: ", p), err) }
1968 | if err := oprot.WriteFieldEnd(); err != nil {
1969 | return thrift.PrependError(fmt.Sprintf("%T write field end error 3:gold: ", p), err) }
1970 | return err
1971 | }
1972 |
1973 | func (p *UserServiceModifyGoldByTokenArgs) String() string {
1974 | if p == nil {
1975 | return ""
1976 | }
1977 | return fmt.Sprintf("UserServiceModifyGoldByTokenArgs(%+v)", *p)
1978 | }
1979 |
1980 | // Attributes:
1981 | // - Success
1982 | type UserServiceModifyGoldByTokenResult struct {
1983 | Success *Result_ `thrift:"success,0" db:"success" json:"success,omitempty"`
1984 | }
1985 |
1986 | func NewUserServiceModifyGoldByTokenResult() *UserServiceModifyGoldByTokenResult {
1987 | return &UserServiceModifyGoldByTokenResult{}
1988 | }
1989 |
1990 | var UserServiceModifyGoldByTokenResult_Success_DEFAULT *Result_
1991 | func (p *UserServiceModifyGoldByTokenResult) GetSuccess() *Result_ {
1992 | if !p.IsSetSuccess() {
1993 | return UserServiceModifyGoldByTokenResult_Success_DEFAULT
1994 | }
1995 | return p.Success
1996 | }
1997 | func (p *UserServiceModifyGoldByTokenResult) IsSetSuccess() bool {
1998 | return p.Success != nil
1999 | }
2000 |
2001 | func (p *UserServiceModifyGoldByTokenResult) Read(iprot thrift.TProtocol) error {
2002 | if _, err := iprot.ReadStructBegin(); err != nil {
2003 | return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
2004 | }
2005 |
2006 |
2007 | for {
2008 | _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
2009 | if err != nil {
2010 | return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
2011 | }
2012 | if fieldTypeId == thrift.STOP { break; }
2013 | switch fieldId {
2014 | case 0:
2015 | if fieldTypeId == thrift.STRUCT {
2016 | if err := p.ReadField0(iprot); err != nil {
2017 | return err
2018 | }
2019 | } else {
2020 | if err := iprot.Skip(fieldTypeId); err != nil {
2021 | return err
2022 | }
2023 | }
2024 | default:
2025 | if err := iprot.Skip(fieldTypeId); err != nil {
2026 | return err
2027 | }
2028 | }
2029 | if err := iprot.ReadFieldEnd(); err != nil {
2030 | return err
2031 | }
2032 | }
2033 | if err := iprot.ReadStructEnd(); err != nil {
2034 | return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
2035 | }
2036 | return nil
2037 | }
2038 |
2039 | func (p *UserServiceModifyGoldByTokenResult) ReadField0(iprot thrift.TProtocol) error {
2040 | p.Success = &Result_{}
2041 | if err := p.Success.Read(iprot); err != nil {
2042 | return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err)
2043 | }
2044 | return nil
2045 | }
2046 |
2047 | func (p *UserServiceModifyGoldByTokenResult) Write(oprot thrift.TProtocol) error {
2048 | if err := oprot.WriteStructBegin("modifyGoldByToken_result"); err != nil {
2049 | return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) }
2050 | if p != nil {
2051 | if err := p.writeField0(oprot); err != nil { return err }
2052 | }
2053 | if err := oprot.WriteFieldStop(); err != nil {
2054 | return thrift.PrependError("write field stop error: ", err) }
2055 | if err := oprot.WriteStructEnd(); err != nil {
2056 | return thrift.PrependError("write struct stop error: ", err) }
2057 | return nil
2058 | }
2059 |
2060 | func (p *UserServiceModifyGoldByTokenResult) writeField0(oprot thrift.TProtocol) (err error) {
2061 | if p.IsSetSuccess() {
2062 | if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil {
2063 | return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) }
2064 | if err := p.Success.Write(oprot); err != nil {
2065 | return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err)
2066 | }
2067 | if err := oprot.WriteFieldEnd(); err != nil {
2068 | return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) }
2069 | }
2070 | return err
2071 | }
2072 |
2073 | func (p *UserServiceModifyGoldByTokenResult) String() string {
2074 | if p == nil {
2075 | return ""
2076 | }
2077 | return fmt.Sprintf("UserServiceModifyGoldByTokenResult(%+v)", *p)
2078 | }
2079 |
2080 |
2081 |
--------------------------------------------------------------------------------