6
0

Compare commits

..

No commits in common. "master" and "v1.1.44" have entirely different histories.

185 changed files with 72 additions and 19827 deletions

12
go.mod
View File

@ -1,13 +1,3 @@
module golib.gaore.com/GaoreGo/gaore-common-sdk-go
go 1.19
require (
github.com/json-iterator/go v1.1.12
github.com/spf13/cast v1.8.0
)
require (
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
)
go 1.19

26
go.sum
View File

@ -1,26 +0,0 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/spf13/cast v1.8.0 h1:gEN9K4b8Xws4EX0+a0reLmhq8moKn7ntRlQYgjPeCDk=
github.com/spf13/cast v1.8.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=

View File

@ -18,40 +18,38 @@ func signRpcRequest(request requests.AcsRequest, signer Signer) (err error) {
if err != nil {
return
}
if signer != nil {
if _, isContainsSign := request.GetQueryParams()["sign"]; isContainsSign {
delete(request.GetQueryParams(), "sign")
}
stringToSign := buildRpcStringToSign(request)
request.SetStringToSign(stringToSign)
signature := signer.Sign(stringToSign, "&")
request.GetQueryParams()["sign"] = signature
debug("GrSdk sign: %s", signature)
debug("GrSdk sign string: %s", stringToSign)
debug("GrSdk sign: \r\n")
if _, isContainsSign := request.GetQueryParams()["sign"]; isContainsSign {
delete(request.GetQueryParams(), "sign")
}
stringToSign := buildRpcStringToSign(request)
request.SetStringToSign(stringToSign)
signature := signer.Sign(stringToSign, "&")
request.GetQueryParams()["sign"] = signature
debug("GrSdk sign: %s", signature)
debug("GrSdk sign string: %s", stringToSign)
debug("GrSdk sign: \r\n")
return
}
func completeRpcSignParams(request requests.AcsRequest, signer Signer) (err error) {
if signer != nil {
var accessKeyFrom string
if accessKeyFrom, err = signer.GetAccessKeyFrom(); err != nil {
return
}
queryParams := request.GetQueryParams()
queryParams["access_time"] = fmt.Sprintf("%d", time.Now().Unix())
queryParams["access_key"], err = signer.GetAccessKeyId()
queryParams["access_from"] = accessKeyFrom
request.GetHeaders()["Gr-Sdk-From"] = accessKeyFrom
if err != nil {
return
}
var accessKeyFrom string
if accessKeyFrom, err = signer.GetAccessKeyFrom(); err != nil {
return
}
request.GetHeaders()["Content-type"] = requests.Form
queryParams := request.GetQueryParams()
queryParams["access_time"] = fmt.Sprintf("%d", time.Now().Unix())
queryParams["access_key"], err = signer.GetAccessKeyId()
queryParams["access_from"] = accessKeyFrom
if err != nil {
return
}
request.GetHeaders()["Content-type"] = requests.Form
request.GetHeaders()["Gr-Sdk-From"] = accessKeyFrom
formString := utils.GetUrlFormedMap(request.GetFormParams())
request.SetContent(bytes.NewBufferString(formString).Bytes())
return

View File

@ -5,7 +5,6 @@ import (
"context"
"crypto/tls"
"fmt"
"github.com/json-iterator/go/extra"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/auth"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/auth/credentials"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
@ -19,7 +18,6 @@ import (
"regexp"
"runtime"
"strings"
"sync"
"time"
)
@ -46,27 +44,6 @@ type Client struct {
httpProxy string
httpsProxy string
noProxy string
header *requests.RefererHeader
}
func (c *Client) SetRefererHeader(header *requests.RefererHeader) {
c.header = header
}
func (c *Client) GetRefererHeader() map[string]string {
var header *requests.RefererHeader
if c.header == nil {
header = &requests.RefererHeader{
TraceId: utils.MakeTraceId(),
}
} else {
header = c.header
}
return map[string]string{
"Referer": header.Referer,
"Traceparent": header.TraceId,
}
}
func (client *Client) GetNoProxy() string {
@ -112,15 +89,11 @@ func (client *Client) Init() (err error) {
func (client *Client) InitWithAccessKey(accessKeyId, accessKeySecret, accessKeyFrom string) (err error) {
config := client.InitWithConfig()
var credential auth.Credential
if accessKeyId != "" {
credential = &credentials.BaseCredential{
AccessKeyId: accessKeyId,
AccessKeySecret: accessKeySecret,
AccessKeyFrom: accessKeyFrom,
}
credential := &credentials.BaseCredential{
AccessKeyId: accessKeyId,
AccessKeySecret: accessKeySecret,
AccessKeyFrom: accessKeyFrom,
}
return client.InitWithOptions(config, credential)
}
@ -158,9 +131,8 @@ func (client *Client) InitWithOptions(config *Config, credential auth.Credential
if config.Timeout > 0 {
client.httpClient.Timeout = config.Timeout
}
if credential != nil {
client.signer, err = auth.NewSignerWithCredential(credential, client.ProcessCommonRequestWithSigner)
}
client.signer, err = auth.NewSignerWithCredential(credential, client.ProcessCommonRequestWithSigner)
return
}
@ -239,7 +211,7 @@ func (client *Client) DoAction(request requests.AcsRequest, response responses.A
}
func (client *Client) DoActionWithSigner(request requests.AcsRequest, response responses.AcsResponse, signer auth.Signer) (err error) {
request.AddHeaders(client.GetRefererHeader())
httpRequest, err := client.buildRequestWithSigner(request, signer)
if err != nil {
return err
@ -387,10 +359,3 @@ func (client *Client) getNoProxy(scheme string) []string {
func hookDo(fn func(req *http.Request) (*http.Response, error)) func(req *http.Request) (*http.Response, error) {
return fn
}
func init() {
once := sync.Once{}
once.Do(func() {
extra.RegisterFuzzyDecoders()
})
}

View File

@ -56,11 +56,6 @@ type Host struct {
Func func(string) string
}
type RefererHeader struct {
Referer string
TraceId string
}
var debug utils.Debug
func init() {
@ -100,7 +95,6 @@ type AcsRequest interface {
GetBodyReader() io.Reader
AddHeaderParam(key, value string)
AddHeaders(headers map[string]string)
addQueryParam(key, value string)
addFormParam(key, value string)
addJsonParam(string, any)
@ -232,12 +226,6 @@ func (request *baseRequest) AddHeaderParam(key, val string) {
request.Headers[key] = val
}
func (request *baseRequest) AddHeaders(headers map[string]string) {
for key, val := range headers {
request.Headers[key] = val
}
}
func (request *baseRequest) addQueryParam(key, val string) {
request.QueryParams[key] = val
}

View File

@ -1,9 +1,9 @@
package responses
import (
"encoding/json"
"errors"
"fmt"
"github.com/json-iterator/go"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"io/ioutil"
"net/http"
@ -89,7 +89,7 @@ func Unmarshal(response AcsResponse, httpResponse *http.Response, format string)
return
}
if _, isCommonResponse := response.(*CommonResponse); isCommonResponse {
if _, isCommonResponse := response.(CommonResponse); isCommonResponse {
return
}
@ -97,10 +97,7 @@ func Unmarshal(response AcsResponse, httpResponse *http.Response, format string)
if contentType, ok := response.GetHttpHeaders()["Content-Type"]; ok {
for _, v := range contentType {
if strings.Contains(v, requests.Json) {
err = jsoniter.Unmarshal(response.GetHttpContentBytes(), response)
if err != nil {
return errors.New("json Unmarshal:" + err.Error())
}
json.Unmarshal(response.GetHttpContentBytes(), response)
break
}
}
@ -111,11 +108,10 @@ func Unmarshal(response AcsResponse, httpResponse *http.Response, format string)
}
if format != "xml" {
err = jsoniter.Unmarshal(response.GetHttpContentBytes(), response)
err = json.Unmarshal(response.GetHttpContentBytes(), response)
if err != nil {
return errors.New("json Unmarshal:" + err.Error())
}
}
return
}

View File

@ -1,69 +0,0 @@
package random
import (
"math/rand"
"time"
"unsafe"
)
type Mode int // 随机数模式
const (
Letter Mode = iota
Number
LetterNumber
LetterHex
)
const (
letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
numbers = "0123456789"
lettersHex = "0123456789abcdef"
letterIdBit = 6
letterIdxMask = 1<<letterIdBit - 1
letterIdxMax = 63 / letterIdBit
)
func StrRandom(n int64) string {
return Random(n, Letter)
}
func NumRandom(n int64) string {
return Random(n, Number)
}
func Random(n int64, mode ...Mode) string {
var baseStr string
mode = append(mode, LetterNumber)
switch mode[0] {
case LetterHex:
baseStr = lettersHex
case Letter:
baseStr = letters
case Number:
baseStr = numbers
case LetterNumber:
fallthrough
default:
baseStr = letters + numbers
}
return random(n, baseStr)
}
func random(n int64, baseStr string) string {
var src = rand.NewSource(time.Now().UnixNano())
b := make([]byte, n)
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(baseStr) {
b[i] = baseStr[idx]
i--
}
cache >>= letterIdBit
remain--
}
return *(*string)(unsafe.Pointer(&b))
}

View File

@ -5,8 +5,8 @@ import (
"crypto/rand"
"encoding/hex"
"fmt"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/utils/random"
"hash"
rand2 "math/rand"
"net/url"
"reflect"
"sort"
@ -36,7 +36,11 @@ func NewUUID() UUID {
}
func RandStringBytes(n int) string {
return random.StrRandom(int64(n))
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand2.Intn(len(letterBytes))]
}
return string(b)
}
func newFromHash(h hash.Hash, ns UUID, name string) UUID {
@ -105,12 +109,3 @@ func InitStructWithDefaultTag(bean interface{}) {
}
}
}
func Md5(data string) string {
s := md5.Sum([]byte(data))
return hex.EncodeToString(s[:])
}
func MakeTraceId() string {
return fmt.Sprintf("00-%s-%s-01", random.Random(32, random.LetterHex), random.Random(16, random.LetterHex))
}

View File

@ -23,7 +23,3 @@ func TestInitStructWithDefaultTag(t *testing.T) {
InitStructWithDefaultTag(testcase)
fmt.Printf("%+v", testcase)
}
func TestMd5(t *testing.T) {
t.Log(Md5("123456"))
}

View File

@ -1,47 +0,0 @@
package asdk
import (
"fmt"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/utils"
"time"
)
const (
VERSION = "2020-11-16"
)
var HOST = requests.Host{
Default: "asdk",
}
type Client struct {
sdk.Client
}
func NewClient() (client *Client, err error) {
client = new(Client)
err = client.Init()
return
}
// GenerateInnerApiSign
// 生成内部接口签名
func GenerateInnerApiSign(ts int64) (int64, string) {
const InnerSignSecret = "sYbfhozSu^@K8~y*"
if ts == 0 {
ts = time.Now().Unix()
}
return ts, utils.Md5(fmt.Sprintf("%d%s", ts, InnerSignSecret))
}
// CreateKickUserReq 踢人
func (c *Client) CreateKickUserReq(req *KickUserReq) (resp *KickUserResp, err error) {
resp = CreateKickUserResp()
err = c.DoAction(req, resp)
if err != nil {
return
}
return
}

View File

@ -1,26 +0,0 @@
package asdk
import (
"fmt"
"testing"
)
// 获取用户累计付费
func TestKickUser(t *testing.T) {
client, err := NewClient()
if err != nil {
panic(err)
}
ts, sign := GenerateInnerApiSign(0)
req := CreateKickUserReq(KickUserParam{
Ts: ts,
Sign: sign,
UserName: "aq36604627",
})
resp, err := client.CreateKickUserReq(req)
if err != nil {
panic(err)
}
fmt.Println(resp.Code, resp.Msg, resp.Data)
}

View File

@ -1,45 +0,0 @@
package asdk
import (
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
"strconv"
)
type KickUserReq struct {
*requests.RpcRequest
}
type KickUserResp struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data struct{} `json:"data"`
TraceId string `json:"trace_id"`
}
type KickUserParam struct {
Ts int64 `json:"ts"`
Sign string `json:"sign"`
UserName string `json:"user_name"`
}
func CreateKickUserReq(data KickUserParam) *KickUserReq {
req := &KickUserReq{
&requests.RpcRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/api/kick")
req.Method = requests.GET
req.QueryParams = map[string]string{
"ts": strconv.FormatInt(data.Ts, 10),
"sign": data.Sign,
"user_name": data.UserName,
}
return req
}
func CreateKickUserResp() *KickUserResp {
return &KickUserResp{
BaseResponse: &responses.BaseResponse{},
}
}

View File

@ -1,162 +0,0 @@
package cs
import (
"errors"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"time"
)
const (
VERSION = "2025-06-10"
)
var HOST = requests.Host{
Default: "cs.api.gaore.com",
}
type Client struct {
sdk.Client
}
func NewClient() (client *Client, err error) {
client = new(Client)
err = client.Init()
return
}
func (client *Client) GetFaq(req *GetFaqRequest) (resp *GetFaqResponse, err error) {
resp = CreateGetFaqResponse()
err = client.DoAction(req, resp)
return
}
func (client *Client) GetUserInfo(req *GetUserInfoRequest) (resp *GetUserInfoResponse, err error) {
resp = CreateGetUserInfoResponse()
err = client.DoAction(req, resp)
return
}
func (client *Client) GetCsUserRoleList(req *GetUserRoleListRequest) (resp *GetUserRoleListResponse, err error) {
resp = CreateGetUserRoleListResponse()
err = client.DoAction(req, resp)
return
}
func (client *Client) GetUserServerList(req *GetUserServerListRequest) (resp *GetUserServerListResponse, err error) {
resp = CreateGetUserServerListResponse()
err = client.DoAction(req, resp)
return
}
func (client *Client) SendSmsCode(req *SendSmsRequest) (resp *SendSmsResponse, err error) {
resp = CreateSendSmsResponse()
err = client.DoAction(req, resp)
return
}
func (client *Client) Upload(req *UploadRequest) (resp *UploadResponse, err error) {
// check file stream
if req.FileStream == nil {
err = errors.New("stream is empty")
return
}
// 必须设置content
req.SetContent(req.FileStream)
// 考虑网络不佳的情况,提高超时时间
req.SetReadTimeout(10 * time.Second)
resp = CreateUploadResponse()
err = client.DoAction(req, resp)
return
}
func (client *Client) GetOrderTemplateDetail(req *OrderTemplateDetailReq) (resp *OrderTemplateDetailResp, err error) {
resp = CreateOrderTemplateDetailResp()
err = client.DoAction(req, resp)
return
}
func (client *Client) GetOrderFurtherPart(req *GetOrderFurtherPartRequest) (resp *GetOrderFurtherPartResponse, err error) {
resp = CreateGetOrderFurtherPartResponse()
err = client.DoAction(req, resp)
return
}
func (client *Client) OrderUrgent(req *OrderUrgentRequest) (resp *OrderUrgentResponse, err error) {
resp = CreateOrderUrgentResponse()
err = client.DoAction(req, resp)
return
}
func (client *Client) OrderUpdateHandle(req *OrderUpdateHandleRequest) (resp *OrderUpdateHandleResponse, err error) {
resp = CreateOrderUpdateHandleResponse()
err = client.DoAction(req, resp)
return
}
func (client *Client) OrderAppraise(req *OrderAppraiseRequest) (resp *OrderAppraiseResponse, err error) {
resp = CreateOrderAppraiseResponse()
err = client.DoAction(req, resp)
return
}
func (client *Client) OrderRestart(req *OrderRestartRequest) (resp *OrderRestartResponse, err error) {
resp = CreateOrderRestartResponse()
err = client.DoAction(req, resp)
return
}
func (client *Client) OrderSubmit(req *OrderSubmitRequest) (resp *OrderSubmitResponse, err error) {
resp = CreateOrderSubmitResponse()
err = client.DoAction(req, resp)
return
}
func (client *Client) OrderFurtherPart(req *OrderFurtherPartRequest) (resp *OrderFurtherPartResponse, err error) {
resp = CreateOrderFurtherPartResponse()
err = client.DoAction(req, resp)
return
}
func (client *Client) OrderRecordList(req *GetWorkOrderRecordListRequest) (resp *GetWorkOrderRecordListResponse, err error) {
resp = CreateGetWorkOrderRecordListResponse()
err = client.DoAction(req, resp)
return
}
func (client *Client) OrderRecordDetail(req *GetWorkOrderRecordDetailReq) (resp *GetWorkOrderRecordDetailResp, err error) {
resp = CreateGetWorkOrderRecordDetailResp()
err = client.DoAction(req, resp)
return
}
func (client *Client) GetFaqDetail(req *GetFaqDetailRequest) (resp *GetFaqDetailResponse, err error) {
resp = CreateGetFaqDetailResponse()
err = client.DoAction(req, resp)
return
}
func (client *Client) GetHotFaqList(req *GetHotFaqRequest) (resp *GetHotFaqResponse, err error) {
resp = CreateGetHotFaqResponse()
err = client.DoAction(req, resp)
return
}
func (client *Client) ClearFaqListCache(req *ClearFaqListCacheRequest) (resp *ClearFaqListCacheResponse, err error) {
resp = CreateClearFaqListCacheResponse()
err = client.DoAction(req, resp)
return
}
func (client *Client) ClearFaqDetailCache(req *ClearFaqDetailCacheRequest) (resp *ClearFaqDetailCacheResponse, err error) {
resp = CreateClearFaqDetailCacheResponse()
err = client.DoAction(req, resp)
return
}
func (client *Client) ClearHotFaqCache(req *ClearHotFaqCacheRequest) (resp *ClearHotFaqCacheResponse, err error) {
resp = CreateClearHotFaqCacheResponse()
err = client.DoAction(req, resp)
return
}
func (client *Client) GetLinkGameConfig(req *GetLinkGameConfigRequest) (resp *GetLinkGameConfigResponse, err error) {
resp = CreateGetLinkGameConfigResponse()
err = client.DoAction(req, resp)
return
}

View File

@ -1,478 +0,0 @@
package cs
import (
"fmt"
"os"
"testing"
)
/**
* 客服工单服务单元测试
*/
// 获取faq树状数据
func TestGetFaq(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
req := CreateGetFaqRequest()
faq, err := client.GetFaq(req)
if err != nil {
t.Error(err)
return
}
fmt.Printf(fmt.Sprintf("%#+v", faq))
}
// 获取玩家基本信息
func TestGetUserInfo(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
req := CreateGetUserInfoRequest("ws45265737")
info, err := client.GetUserInfo(req)
if err != nil {
t.Error(err)
return
}
fmt.Printf(fmt.Sprintf("%v", info))
}
// 获取玩家角色列表
func TestGetUserRoleList(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
req := CreateGetUserRoleListRequest(int64(63610626), int64(2850))
info, err := client.GetCsUserRoleList(req)
if err != nil {
t.Error(err)
return
}
if info.Code != 0 {
t.Error("获取玩家角色列表失败")
fmt.Printf(fmt.Sprintf("%v", info))
return
}
fmt.Printf(fmt.Sprintf("%v", info))
}
// 获取玩家区服列表
func TestGetUserServerList(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
req := CreateGetUserServerListRequest(int64(63610626), int64(2850))
info, err := client.GetUserServerList(req)
if err != nil {
t.Error(err)
return
}
if info.Code != 0 {
t.Error("获取玩家区服列表失败")
fmt.Printf(fmt.Sprintf("%v", info))
return
}
fmt.Printf(fmt.Sprintf("%v", info))
}
// 给玩家发送短信
func TestSendSms(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
req := CreateSendSmsRequest(SendSmsReq{
Phone: "13725263463",
})
info, err := client.SendSmsCode(req)
if err != nil {
t.Error(err)
return
}
if info.Code != 0 {
t.Error("给玩家发送短信失败")
}
fmt.Printf(fmt.Sprintf("%v", info))
}
// 工单图片上传
func TestUpload(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
// 读取文件流
file, err := os.ReadFile("test.png")
if err != nil {
t.Error(err)
return
}
req := CreateUploadRequest()
req.FileStream = file
res, err := client.Upload(req)
if err != nil {
t.Error(err)
return
}
if res.Code != 0 {
t.Error("工单图片上传失败")
}
fmt.Printf(fmt.Sprintf("%v", res))
}
// 工单模板查询
func TestGetOrderTemplateDetail(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
templateId := int64(12)
req := CreateOrderTemplateDetailReq(templateId)
res, err := client.GetOrderTemplateDetail(req)
if err != nil {
t.Error(err)
return
}
if res.Code != 0 {
t.Error("工单模板查询失败")
}
fmt.Printf(fmt.Sprintf("%v", res))
}
// 工单补充字段设置
func TestGetOrderFurtherPart(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
req := CreateGetOrderFurtherPartRequest(GetOrderFurtherPartParam{
OrderNum: "20250605092301764049"})
res, err := client.GetOrderFurtherPart(req)
if err != nil {
t.Error(err)
return
}
if res.Code != 0 {
t.Error("工单补充字段设置获取失败")
}
fmt.Printf(fmt.Sprintf("%v", res))
}
// 用户催单
func TestOrderUrgent(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
req := CreateOrderUrgentRequest(OrderUrgentParam{
OrderNum: "20250530173554491048"})
res, err := client.OrderUrgent(req)
if err != nil {
t.Error(err)
return
}
if res.Code != 0 {
t.Error("用户催单失败")
}
fmt.Printf(fmt.Sprintf("%v", res))
}
// 用户更新工单处理标识
func TestOrderUpdateHandle(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
req := CreateOrderUpdateHandleRequest(OrderUpdateHandleParam{
IsHandle: 1,
OrderNum: "20250530173554491048"})
res, err := client.OrderUpdateHandle(req)
if err != nil {
t.Error(err)
return
}
if res.Code != 0 {
t.Error("用户催单失败")
}
fmt.Printf(fmt.Sprintf("%v", res))
}
// 用户评价工单
func TestOrderAppraise(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
req := CreateOrderAppraiseRequest(OrderAppraiseParam{
OrderNum: "20250530173554491048",
Score: 5,
})
res, err := client.OrderAppraise(req)
if err != nil {
t.Error(err)
return
}
if res.Code != 0 {
t.Error("用户评价失败")
}
fmt.Printf(fmt.Sprintf("%v", res))
}
// 工单重启
func TestOrderRestart(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
req := CreateOrderRestartRequest(OrderRestartParam{
OrderNum: "20250530173554491048",
SysRemarkContent: "模拟用户重启",
SysRemarkPic: []string{},
})
res, err := client.OrderRestart(req)
if err != nil {
t.Error(err)
return
}
if res.Code != 0 {
t.Error("工单重启失败")
}
fmt.Printf(fmt.Sprintf("%v", res))
}
// 提交工单
func TestOrderSubmit(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
req := CreateOrderSubmitRequest(OrderSubmitParam{
SysGameId: 7874,
SysUserName: "rz35990497",
SysUid: 221016372,
SysRoleId: "265500394",
SysRoleName: "好玩的尼",
SysServerName: "碧水连天",
SysOrderTemplateCode: "findAccount",
SysDetail: "测试go-common改动。",
SysPhone: "13725263463",
ApplyIp: "192.168.1.202",
SysOrderParts: []OrderSubmitPart{
{
PartKey: "email",
PartName: "联系邮箱",
PartValue: "kingson2011@126.com",
PicValue: nil,
},
{
PartKey: "pay_pic",
PartName: "充值凭证",
PartValue: "",
PicValue: []string{
"uploads/068/068eefab055a96ae404db19b7a121898.jpeg",
"uploads/908/90822cca4e87ed49acaf82050dd3ac09.jpeg",
},
},
},
SysSmsCode: "7204",
})
res, err := client.OrderSubmit(req)
if err != nil {
t.Error(err)
return
}
if res.Code != 0 {
t.Error("工单提交失败")
}
fmt.Printf(fmt.Sprintf("%v", res))
}
// 用户工单补充资料
func TestOrderFurtherPart(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
req := CreateOrderFurtherPartRequest(OrderFurtherPartParam{
OrderNum: "20250611160840208567",
OrderParts: []OrderSubmitPart{
{
PartKey: "game_name",
PartName: "游戏名称",
PartValue: "镇魂街:最终章",
},
},
})
res, err := client.OrderFurtherPart(req)
if err != nil {
t.Error(err)
return
}
if res.Code != 0 {
t.Error("用户工单补充资料失败")
}
fmt.Printf(fmt.Sprintf("%v", res))
}
// 工单列表查询
func TestGetWorkOrderRecordList(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
req := CreateGetWorkOrderRecordListRequest(GetWorkOrderRecordListParam{
HandleStatus: "",
UserName: "ws45265737",
GameId: 7991,
Page: 1,
PageSize: 20,
})
res, err := client.OrderRecordList(req)
if err != nil {
t.Error(err)
return
}
if res.Code != 0 {
t.Error("工单列表查询失败")
}
fmt.Printf(fmt.Sprintf("%v", res))
}
// 工单详情查询
func TestOrderRecordDetail(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
req := CreateGetWorkOrderRecordDetailRequest(OrderDetailParam{
OrderNum: "20250611160840208567",
})
res, err := client.OrderRecordDetail(req)
if err != nil {
t.Error(err)
return
}
if res.Code != 0 {
t.Error("工单详情查询失败")
}
fmt.Printf(fmt.Sprintf("%v", res))
}
// 获取faq详情
func TestGetFaqDetail(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
req := CreateGetFaqDetailRequest(FaqDetailRequest{
Id: int64(31),
})
res, err := client.GetFaqDetail(req)
if err != nil {
t.Error(err)
return
}
if res.Code != 0 || res.Data.Id == 0 {
t.Error("获取faq详情失败")
}
fmt.Printf(fmt.Sprintf("%v", res))
}
// 获取热门faq
func TestGetFaqHotList(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
req := CreateGetHotFaqRequest()
res, err := client.GetHotFaqList(req)
if err != nil {
t.Error(err)
return
}
if res.Code != 0 || len(res.Data) == 0 {
t.Error("获取热门faq失败")
}
fmt.Printf(fmt.Sprintf("%v", res))
}
// 清理faq列表缓存
func TestClearFaqListCache(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
req := CreateClearFaqListCacheRequest()
res, err := client.ClearFaqListCache(req)
if err != nil {
t.Error(err)
}
if res.Code != 0 {
t.Error("清理faq列表缓存失败")
}
fmt.Printf(fmt.Sprintf("%v", res))
}
// 清理faq详情缓存
func TestClearFaqDetailCache(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
req := CreateClearFaqDetailCacheRequest(FaqDetailRequest{
Id: int64(30),
})
res, err := client.ClearFaqDetailCache(req)
if err != nil {
t.Error(err)
}
if res.Code != 0 {
t.Error("清理faq详情缓存失败")
}
fmt.Printf(fmt.Sprintf("%v", res))
}
// 清理热门faq缓存
func TestClearHotFaqCache(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
req := CreateClearHotFaqCacheRequest()
res, err := client.ClearHotFaqCache(req)
if err != nil {
t.Error(err)
}
if res.Code != 0 {
t.Error("清理热门faq缓存失败")
}
fmt.Printf(fmt.Sprintf("%v", res))
}
// 获取人工客服链接,主体与游戏参数配置详情
func TestGetLinkGameConfigDetail(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
req := CreateGetLinkGameConfigRequest(LinkGameConfigRequest{
Company: "JJW",
})
res, err := client.GetLinkGameConfig(req)
if err != nil {
t.Error(err)
return
}
if res.Code != 0 || res.Data.SubjectSign == "" {
t.Error("获取人工客服链接,主体与游戏参数配置详情失败")
}
fmt.Printf(fmt.Sprintf("%v", res.Data))
}

View File

@ -1,45 +0,0 @@
package cs
import (
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
)
// 中旭人工客服链接,主体与游戏配置
type LinkGameConfig struct {
SubjectSign string `json:"subject_sign"`
SubjectName string `json:"subject_name"`
LinkGameId int64 `json:"link_game_id"`
CreatedAt string `json:"created_at"`
}
type GetLinkGameConfigRequest struct {
*requests.JsonRequest
Company string `position:"Json" field:"company"`
}
type GetLinkGameConfigResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data *LinkGameConfig `json:"data"`
}
type LinkGameConfigRequest struct {
Company string `json:"company"`
}
func CreateGetLinkGameConfigRequest(param LinkGameConfigRequest) (req *GetLinkGameConfigRequest) {
req = &GetLinkGameConfigRequest{
JsonRequest: &requests.JsonRequest{},
Company: param.Company,
}
req.InitWithApiInfo(HOST, VERSION, "/v1/config/get_link_game_config")
req.Method = requests.POST
return
}
func CreateGetLinkGameConfigResponse() (response *GetLinkGameConfigResponse) {
response = &GetLinkGameConfigResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -1,203 +0,0 @@
package cs
import (
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
)
// Faq 树状结构
type Faq struct {
Id int64 `json:"id"`
ParentId int64 `json:"parent_id"`
Title string `json:"title"`
Answer string `json:"answer"`
Type int64 `json:"type"`
WorkOrderTemplateId int64 `json:"work_order_template_id"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
ProcessFlow string `json:"process_flow"`
Children []*Faq `json:"children"`
}
type GetFaqRequest struct {
*requests.RpcRequest
}
type GetFaqResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data Faq `json:"data"`
}
func CreateGetFaqRequest() (req *GetFaqRequest) {
req = &GetFaqRequest{
RpcRequest: &requests.RpcRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/v1/faq/list")
req.Method = requests.POST
return
}
func CreateGetFaqResponse() (response *GetFaqResponse) {
response = &GetFaqResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}
// FaqDetail Faq详情
type FaqDetail struct {
Id int64 `json:"id"`
ParentId int64 `json:"parent_id"`
Title string `json:"title"`
Answer string `json:"answer"`
Type int64 `json:"type"`
WorkOrderTemplateId int64 `json:"work_order_template_id"`
ProcessFlow string `json:"process_flow"`
WorkOrderTemplateCode string `json:"work_order_template_code"`
}
type GetFaqDetailRequest struct {
*requests.JsonRequest
Id int64 `position:"Json" field:"id"`
}
type GetFaqDetailResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data *FaqDetail `json:"data"`
}
type FaqDetailRequest struct {
Id int64 `json:"id"`
}
func CreateGetFaqDetailRequest(param FaqDetailRequest) (req *GetFaqDetailRequest) {
req = &GetFaqDetailRequest{
JsonRequest: &requests.JsonRequest{},
Id: param.Id,
}
req.InitWithApiInfo(HOST, VERSION, "/v1/faq/detail")
req.Method = requests.POST
return
}
func CreateGetFaqDetailResponse() (response *GetFaqDetailResponse) {
response = &GetFaqDetailResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}
// 热门faq列表
type HotFaq struct {
Id int64 `json:"id"`
Title string `json:"title"`
ParentId int64 `json:"parent_id"`
ParentTitle string `json:"parent_title"`
}
type GetHotFaqRequest struct {
*requests.JsonRequest
}
type GetHotFaqResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data []HotFaq `json:"data"`
}
func CreateGetHotFaqRequest() (req *GetHotFaqRequest) {
req = &GetHotFaqRequest{
JsonRequest: &requests.JsonRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/v1/faq/hot_list")
req.Method = requests.POST
return
}
func CreateGetHotFaqResponse() (response *GetHotFaqResponse) {
response = &GetHotFaqResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}
// 清理faq树缓存
type ClearFaqListCacheRequest struct {
*requests.JsonRequest
}
type ClearFaqListCacheResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
}
func CreateClearFaqListCacheRequest() (req *ClearFaqListCacheRequest) {
req = &ClearFaqListCacheRequest{
JsonRequest: &requests.JsonRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/v1/faq/clear_list_cache")
req.Method = requests.POST
return
}
func CreateClearFaqListCacheResponse() (response *ClearFaqListCacheResponse) {
response = &ClearFaqListCacheResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}
// 清理faq详情缓存
type ClearFaqDetailCacheRequest struct {
*requests.JsonRequest
Id int64 `position:"Json" field:"id"`
}
type ClearFaqDetailCacheResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
}
func CreateClearFaqDetailCacheRequest(param FaqDetailRequest) (req *ClearFaqDetailCacheRequest) {
req = &ClearFaqDetailCacheRequest{
JsonRequest: &requests.JsonRequest{},
Id: param.Id,
}
req.InitWithApiInfo(HOST, VERSION, "/v1/faq/clear_detail_cache")
req.Method = requests.POST
return
}
func CreateClearFaqDetailCacheResponse() (response *ClearFaqDetailCacheResponse) {
response = &ClearFaqDetailCacheResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}
// 清理热门faq缓存
type ClearHotFaqCacheRequest struct {
*requests.JsonRequest
}
type ClearHotFaqCacheResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
}
func CreateClearHotFaqCacheRequest() (req *ClearHotFaqCacheRequest) {
req = &ClearHotFaqCacheRequest{
JsonRequest: &requests.JsonRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/v1/faq/clear_hot_list_cache")
req.Method = requests.POST
return
}
func CreateClearHotFaqCacheResponse() (response *ClearHotFaqCacheResponse) {
response = &ClearHotFaqCacheResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -1,320 +0,0 @@
package cs
import (
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
)
/**
* 客服工单相关方法
*/
type UploadRequest struct {
*requests.StreamRequest
FileStream []byte
}
type UploadResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
FileName string `json:"file_name"`
FileUrl string `json:"file_url"`
FilePath string `json:"file_path"`
}
TraceId string `json:"trace_id"`
}
func CreateUploadRequest() (req *UploadRequest) {
req = &UploadRequest{
StreamRequest: &requests.StreamRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/v1/work_order/upload_image")
req.Method = requests.POST
return
}
func CreateUploadResponse() (resp *UploadResponse) {
return &UploadResponse{
BaseResponse: &responses.BaseResponse{},
}
}
// 获取工单补充字段设置
// GetOrderFurtherPartParam 请求参数
type GetOrderFurtherPartParam struct {
OrderNum string `json:"order_num"`
}
type GetOrderFurtherPartRequest struct {
*requests.JsonRequest
OrderNum string `position:"Json" field:"order_num"`
}
type OrderFurtherPart struct {
OrderNum string `json:"order_num"`
FurtherParts []*OrderPart `json:"further_parts"`
}
type GetOrderFurtherPartResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Data OrderFurtherPart `json:"data"`
Msg string `json:"msg"`
}
func CreateGetOrderFurtherPartRequest(param GetOrderFurtherPartParam) (req *GetOrderFurtherPartRequest) {
req = &GetOrderFurtherPartRequest{
JsonRequest: &requests.JsonRequest{},
OrderNum: param.OrderNum,
}
req.InitWithApiInfo(HOST, VERSION, "/v1/work_order/get_order_further_part")
req.Method = requests.POST
return
}
func CreateGetOrderFurtherPartResponse() (resp *GetOrderFurtherPartResponse) {
return &GetOrderFurtherPartResponse{
BaseResponse: &responses.BaseResponse{},
}
}
// OrderUrgentParam 用户催单
type OrderUrgentParam struct {
OrderNum string `json:"order_num"`
}
type OrderUrgentRequest struct {
*requests.JsonRequest
OrderNum string `position:"Json" field:"order_num"`
}
type OrderUrgentResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
}
func CreateOrderUrgentRequest(param OrderUrgentParam) (req *OrderUrgentRequest) {
req = &OrderUrgentRequest{
JsonRequest: &requests.JsonRequest{},
OrderNum: param.OrderNum,
}
req.InitWithApiInfo(HOST, VERSION, "/v1/work_order/order_urgent")
req.Method = requests.POST
return
}
func CreateOrderUrgentResponse() (resp *OrderUrgentResponse) {
return &OrderUrgentResponse{
BaseResponse: &responses.BaseResponse{},
}
}
// OrderUpdateHandleParam 更新工单处理标识
type OrderUpdateHandleParam struct {
OrderNum string `json:"order_num"`
IsHandle int64 `json:"is_handle"`
}
type OrderUpdateHandleRequest struct {
*requests.JsonRequest
OrderNum string `position:"Json" field:"order_num"`
IsHandle int64 `position:"Json" field:"is_handle"`
}
type OrderUpdateHandleResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
}
func CreateOrderUpdateHandleRequest(param OrderUpdateHandleParam) (req *OrderUpdateHandleRequest) {
req = &OrderUpdateHandleRequest{
JsonRequest: &requests.JsonRequest{},
OrderNum: param.OrderNum,
IsHandle: param.IsHandle,
}
req.InitWithApiInfo(HOST, VERSION, "/v1/work_order/order_handle")
req.Method = requests.POST
return
}
func CreateOrderUpdateHandleResponse() (resp *OrderUpdateHandleResponse) {
return &OrderUpdateHandleResponse{
BaseResponse: &responses.BaseResponse{},
}
}
// OrderAppraiseParam 用户评价工单
type OrderAppraiseParam struct {
OrderNum string `json:"order_num"`
Score int `json:"score"`
}
type OrderAppraiseRequest struct {
*requests.JsonRequest
OrderNum string `position:"Json" field:"order_num"`
Score int `position:"Json" field:"score"`
}
type OrderAppraiseResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
}
func CreateOrderAppraiseRequest(param OrderAppraiseParam) (req *OrderAppraiseRequest) {
req = &OrderAppraiseRequest{
JsonRequest: &requests.JsonRequest{},
OrderNum: param.OrderNum,
Score: param.Score,
}
req.InitWithApiInfo(HOST, VERSION, "/v1/work_order/order_appraise")
req.Method = requests.POST
return
}
func CreateOrderAppraiseResponse() (resp *OrderAppraiseResponse) {
return &OrderAppraiseResponse{
BaseResponse: &responses.BaseResponse{},
}
}
// OrderRestartParam 用户重启工单
type OrderRestartParam struct {
OrderNum string `json:"order_num"`
SysRemarkContent string `json:"sys_remark_content"`
SysRemarkPic []string `json:"sys_remark_pic"`
UserName string `json:"user_name"`
}
type OrderRestartRequest struct {
*requests.JsonRequest
OrderNum string `position:"Json" field:"order_num"`
SysRemarkContent string `position:"Json" field:"sys_remark_content"`
SysRemarkPic []string `position:"Json" field:"sys_remark_pic"`
UserName string `position:"Json" field:"user_name"`
}
type OrderRestartResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
}
func CreateOrderRestartRequest(param OrderRestartParam) (req *OrderRestartRequest) {
req = &OrderRestartRequest{
JsonRequest: &requests.JsonRequest{},
OrderNum: param.OrderNum,
SysRemarkContent: param.SysRemarkContent,
SysRemarkPic: param.SysRemarkPic,
UserName: param.UserName,
}
req.InitWithApiInfo(HOST, VERSION, "/v1/work_order/order_restart")
req.Method = requests.POST
return
}
func CreateOrderRestartResponse() (resp *OrderRestartResponse) {
return &OrderRestartResponse{
BaseResponse: &responses.BaseResponse{},
}
}
// OrderSubmitParam 工单提交
type OrderSubmitParam struct {
SysGameId int64 `json:"sys_game_id"`
SysUserName string `json:"sys_user_name"`
SysUid int64 `json:"sys_uid"`
SysRoleId string `json:"sys_role_id"`
SysRoleName string `json:"sys_role_name"`
SysServerName string `json:"sys_server_name"`
SysOrderTemplateCode string `json:"sys_order_template_code"`
SysDetail string `json:"sys_detail"`
SysPhone string `json:"sys_phone"`
ApplyIp string `json:"apply_ip"`
SysOrderParts []OrderSubmitPart `json:"sys_order_parts"`
SysSmsCode string `json:"sys_sms_code"`
}
type OrderSubmitPart struct {
PartId int64 `json:"part_id"`
PartKey string `json:"part_key"`
PartName string `json:"part_name"`
PartValue string `json:"part_value"`
PartType int64 `json:"part_type"`
PicValue []string `json:"pic_value"`
}
type OrderSubmitRequest struct {
*requests.JsonRequest
SysGameId int64 `position:"Json" field:"sys_game_id"`
SysUserName string `position:"Json" field:"sys_user_name"`
SysUid int64 `position:"Json" field:"sys_uid"`
SysRoleId string `position:"Json" field:"sys_role_id"`
SysRoleName string `position:"Json" field:"sys_role_name"`
SysServerName string `position:"Json" field:"sys_server_name"`
SysOrderTemplateCode string `position:"Json" field:"sys_order_template_code"`
SysDetail string `position:"Json" field:"sys_detail"`
SysPhone string `position:"Json" field:"sys_phone"`
ApplyIp string `position:"Json" field:"apply_ip"`
SysOrderParts []OrderSubmitPart `position:"Json" field:"sys_order_parts"`
SysSmsCode string `position:"Json" field:"sys_sms_code"`
}
type OrderSubmitResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
OrderNum string `json:"order_num"`
} `json:"data"`
}
func CreateOrderSubmitRequest(param OrderSubmitParam) (req *OrderSubmitRequest) {
req = &OrderSubmitRequest{
JsonRequest: &requests.JsonRequest{},
SysGameId: param.SysGameId,
SysUserName: param.SysUserName,
SysUid: param.SysUid,
SysRoleId: param.SysRoleId,
SysRoleName: param.SysRoleName,
SysServerName: param.SysServerName,
SysOrderTemplateCode: param.SysOrderTemplateCode,
SysDetail: param.SysDetail,
SysPhone: param.SysPhone,
ApplyIp: param.ApplyIp,
SysOrderParts: param.SysOrderParts,
SysSmsCode: param.SysSmsCode,
}
req.InitWithApiInfo(HOST, VERSION, "/v1/work_order/order_submit")
req.Method = requests.POST
return
}
func CreateOrderSubmitResponse() (resp *OrderSubmitResponse) {
return &OrderSubmitResponse{
BaseResponse: &responses.BaseResponse{},
}
}
// OrderFurtherPartParam 工单补充资料
type OrderFurtherPartParam struct {
OrderNum string `json:"order_num"`
OrderParts []OrderSubmitPart `json:"order_parts"`
UserName string `json:"user_name"`
}
type OrderFurtherPartRequest struct {
*requests.JsonRequest
OrderNum string `position:"Json" field:"order_num"`
OrderParts []OrderSubmitPart `position:"Json" field:"order_parts"`
UserName string `position:"Json" field:"user_name"`
}
type OrderFurtherPartResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
}
func CreateOrderFurtherPartRequest(param OrderFurtherPartParam) (req *OrderFurtherPartRequest) {
req = &OrderFurtherPartRequest{
JsonRequest: &requests.JsonRequest{},
OrderNum: param.OrderNum,
OrderParts: param.OrderParts,
UserName: param.UserName,
}
req.InitWithApiInfo(HOST, VERSION, "/v1/work_order/order_further_data")
req.Method = requests.POST
return
}
func CreateOrderFurtherPartResponse() (resp *OrderFurtherPartResponse) {
return &OrderFurtherPartResponse{
BaseResponse: &responses.BaseResponse{},
}
}

View File

@ -1,140 +0,0 @@
package cs
import (
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
)
// 获取客服工单列表
type GetWorkOrderRecordListParam struct {
OrderNum string `position:"Json" field:"order_num"`
Page int64 `position:"Json" field:"page"`
PageSize int64 `position:"Json" field:"page_size"`
UserName string `position:"Json" field:"user_name"`
GameId int64 `position:"Json" field:"game_id"`
HandleStatus string `position:"Json" field:"handle_status"`
}
type OrderRecord struct {
OrderNum string `json:"order_num"`
WorkOrderTemplateFirstLevelName string `json:"work_order_template_first_level_name"`
UserName string `json:"user_name"`
GameId int64 `json:"game_id"`
GameName string `json:"game_name"`
RoleId string `json:"role_id"`
RoleName string `json:"role_name"`
ServerName string `json:"server_name"`
Detail string `json:"detail"`
ApplyTime string `json:"apply_time"`
HandleStatus string `json:"handle_status"`
HandleStatusName string `json:"handle_status_name"`
IsUrgent int64 `json:"is_urgent"`
IsAppraise int64 `json:"is_appraise"`
FinishTime string `json:"finish_time"`
OrderParts []*OrderSubmitPart `json:"order_parts"`
Id int64 `json:"id"`
WorkOrderTemplateFirstLevelId int64 `json:"work_order_template_first_level_id"`
WorkOrderTemplateId int64 `json:"work_order_template_id"`
WorkOrderTemplateName string `json:"work_order_template_name"`
Uid int64 `json:"uid"`
OrderStatus string `json:"order_status"`
OrderStatusName string `json:"order_status_name"`
}
// PageInfoResp 分页响应
type PageInfoResp struct {
Page int `json:"page"`
PageSize int `json:"page_size"`
TotalNumber int `json:"total_number"`
TotalPage int `json:"total_page"`
}
type GetWorkOrderRecordListResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Data struct {
Data []*OrderRecord `json:"data"`
PageInfo *PageInfoResp `json:"page_info"`
} `json:"data"`
Msg string `json:"msg"`
TraceId string `json:"trace_id"`
}
type GetWorkOrderRecordListRequest struct {
*requests.JsonRequest
OrderNum string `position:"Json" field:"order_num"`
Page int64 `position:"Json" field:"page"`
PageSize int64 `position:"Json" field:"page_size"`
UserName string `position:"Json" field:"user_name"`
GameId int64 `position:"Json" field:"game_id"`
HandleStatus string `position:"Json" field:"handle_status"`
}
func CreateGetWorkOrderRecordListRequest(param GetWorkOrderRecordListParam) (req *GetWorkOrderRecordListRequest) {
req = &GetWorkOrderRecordListRequest{
JsonRequest: &requests.JsonRequest{},
}
req.OrderNum = param.OrderNum
req.Page = param.Page
req.PageSize = param.PageSize
req.UserName = param.UserName
req.GameId = param.GameId
req.HandleStatus = param.HandleStatus
req.InitWithApiInfo(HOST, VERSION, "/v1/work_order/order_record_list")
req.Method = requests.POST
return
}
func CreateGetWorkOrderRecordListResponse() (resp *GetWorkOrderRecordListResponse) {
resp = &GetWorkOrderRecordListResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}
// 工单详情
type OrderDetailParam struct {
OrderNum string `json:"order_num"`
}
type OrderLog struct {
Id int64 `json:"id"`
ApplyCount int64 `json:"apply_count"`
ActionType string `json:"action_type"`
PlayerLinkType string `json:"player_link_type"`
PlayerLinkTypeName string `json:"player_link_type_name"`
Content []*OrderSubmitPart `json:"content"`
PicContent []*OrderSubmitPart `json:"pic_content"`
CreatedAt string `json:"created_at"`
}
type OrderDetail struct {
OrderRecord *OrderRecord `json:"order_record"`
OrderLogs []*OrderLog `json:"order_logs"`
}
type GetWorkOrderRecordDetailResp struct {
*responses.BaseResponse
Code int `json:"code"`
Data OrderDetail `json:"data"`
Msg string `json:"msg"`
}
type GetWorkOrderRecordDetailReq struct {
*requests.JsonRequest
OrderNum string `position:"Json" field:"order_num"`
}
func CreateGetWorkOrderRecordDetailRequest(param OrderDetailParam) (req *GetWorkOrderRecordDetailReq) {
req = &GetWorkOrderRecordDetailReq{
JsonRequest: &requests.JsonRequest{},
}
req.OrderNum = param.OrderNum
req.InitWithApiInfo(HOST, VERSION, "/v1/work_order/order_record_detail")
req.Method = requests.POST
return
}
func CreateGetWorkOrderRecordDetailResp() (resp *GetWorkOrderRecordDetailResp) {
resp = &GetWorkOrderRecordDetailResp{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -1,55 +0,0 @@
package cs
import (
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
)
// OrderTemplate 工单模板
type OrderTemplate struct {
Id int64 `json:"id"`
Name string `json:"name"`
UniqueCode string `json:"unique_code"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
TemplateParts []*OrderPart `json:"template_parts"`
}
// OrderPart 工单字段
type OrderPart struct {
Id int64 `json:"id"`
PartName string `json:"part_name"`
PartKey string `json:"part_key"`
PartType int64 `json:"part_type"`
IsRequire int64 `json:"is_require"`
TipsContent string `json:"tips_content"`
MaxNum int64 `json:"max_num"`
}
type OrderTemplateDetailReq struct {
*requests.JsonRequest
Id int64 `position:"Json" field:"id"`
}
type OrderTemplateDetailResp struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data OrderTemplate `json:"data"`
}
func CreateOrderTemplateDetailReq(templateId int64) (req *OrderTemplateDetailReq) {
req = &OrderTemplateDetailReq{
JsonRequest: &requests.JsonRequest{},
Id: templateId,
}
req.InitWithApiInfo(HOST, VERSION, "/v1/work_order_template/detail")
req.Method = requests.POST
return
}
func CreateOrderTemplateDetailResp() (response *OrderTemplateDetailResp) {
response = &OrderTemplateDetailResp{
BaseResponse: &responses.BaseResponse{},
}
return
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

View File

@ -1,157 +0,0 @@
package cs
import (
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
)
/**
* 获取玩家用户相关信息
*/
// UserInfo 用户信息
type UserInfo struct {
UserName string `json:"user_name"`
Uid int64 `json:"uid"`
Telephone string `json:"telephone"`
}
type GetUserInfoRequest struct {
*requests.RpcRequest
}
type GetUserInfoResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data UserInfo `json:"data"`
}
func CreateGetUserInfoRequest(userName string) (req *GetUserInfoRequest) {
req = &GetUserInfoRequest{
RpcRequest: &requests.RpcRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/v1/user/info")
req.FormParams = map[string]string{
"user_name": userName,
}
req.Method = requests.POST
return
}
func CreateGetUserInfoResponse() (response *GetUserInfoResponse) {
response = &GetUserInfoResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}
// UserRoleInfo 玩家角色信息
type UserRoleInfo struct {
Uid int64 `json:"uid"`
RoleName string `json:"role_name"`
RoleId string `json:"role_id"`
}
type GetUserRoleListRequest struct {
*requests.JsonRequest
}
type GetUserRoleListResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data []UserRoleInfo `json:"data"`
}
func CreateGetUserRoleListRequest(uId int64, gameId int64) (req *GetUserRoleListRequest) {
req = &GetUserRoleListRequest{
JsonRequest: &requests.JsonRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/v1/user/role_list")
req.JsonParams["uid"] = uId
req.JsonParams["game_id"] = gameId
req.Method = requests.POST
return
}
func CreateGetUserRoleListResponse() (response *GetUserRoleListResponse) {
response = &GetUserRoleListResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}
// UserServerInfo 玩家区服信息
type UserServerInfo struct {
ServerName string `json:"server_name"`
}
type GetUserServerListRequest struct {
*requests.JsonRequest
}
type GetUserServerListResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data []UserServerInfo `json:"data"`
}
func CreateGetUserServerListRequest(uId int64, gameId int64) (req *GetUserServerListRequest) {
req = &GetUserServerListRequest{
JsonRequest: &requests.JsonRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/v1/user/server_list")
req.JsonParams["uid"] = uId
req.JsonParams["game_id"] = gameId
req.Method = requests.POST
return
}
func CreateGetUserServerListResponse() (response *GetUserServerListResponse) {
response = &GetUserServerListResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}
type SendSmsReq struct {
Phone string `json:"phone"`
}
// SendSmsResp 发送短信返回
type SendSmsResp struct {
// 短信发送时间戳,工单模块 有效期5分钟
SendCodeTime int64 `json:"send_code_time"`
}
type SendSmsRequest struct {
*requests.JsonRequest
Phone string `position:"Json" field:"phone"`
}
type SendSmsResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data SendSmsResp `json:"data"`
}
func CreateSendSmsRequest(param SendSmsReq) (req *SendSmsRequest) {
req = &SendSmsRequest{
JsonRequest: &requests.JsonRequest{},
Phone: param.Phone,
}
req.InitWithApiInfo(HOST, VERSION, "/v1/user/send_sms")
req.Method = requests.POST
return
}
func CreateSendSmsResponse() (response *SendSmsResponse) {
response = &SendSmsResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -1,43 +0,0 @@
package game
import (
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
)
type ChannelInfoReq struct {
*requests.RpcRequest
ChannelId int64 `position:"Body" field:"channelId"`
ChannelKey string `position:"Body" field:"channelKey"`
}
type ChannelInfoResp struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data map[int64]struct {
Id int64 `json:"id"`
PlatKey string `json:"plat_key"`
PlatName string `json:"plat_name"`
PlatCompany string `json:"plat_company"`
PlatUrl string `json:"plat_url"`
Company string `json:"company"`
PlatCategoryId int64 `json:"plat_category_id"`
CategoryName string `json:"category_name"`
} `json:"data"`
}
func CreateChannelInfoReq() *ChannelInfoReq {
req := &ChannelInfoReq{
RpcRequest: &requests.RpcRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/api/channel/getChannelInfo")
return req
}
func CreateChannelInfoResp() *ChannelInfoResp {
resp := &ChannelInfoResp{
BaseResponse: &responses.BaseResponse{},
}
return resp
}

View File

@ -6,7 +6,7 @@ import (
)
const (
VERSION = "2025-05-28"
VERSION = "2020-11-16"
)
var HOST = requests.Host{
@ -29,97 +29,3 @@ func (c *Client) GetGameOsInfo(req *GetGameOsInfoReq) (resp *GetGameOsInfoResp,
err = c.DoAction(req, resp)
return
}
// GetGameInfo 获取游戏信息
func (c *Client) GetGameInfo(req *GetGameInfoReq) (resp *GetGameInfoResp, err error) {
resp = CreateGetGameInfoByIdResp()
err = c.DoAction(req, resp)
return
}
func (c *Client) GetChannelInfo(req *ChannelInfoReq) (resp *ChannelInfoResp, err error) {
resp = CreateChannelInfoResp()
err = c.DoAction(req, resp)
return
}
func (c *Client) GetLoginInfoById(req *GetLoginInfoByIdReq) (resp *GetLoginInfoByIdResp, err error) {
resp = CreateGetLoginInfoByIdResp()
err = c.DoAction(req, resp)
return
}
func (c *Client) GetProtocolByGameId(req *GetProtocolByGameIdRep) (resp *GetProtocolByGameIdResp, err error) {
resp = CreateGetProtocolByGameIdResp()
err = c.DoAction(req, resp)
return
}
// GetGameSimpleList 获取子游戏简单列表
func (c *Client) GetGameSimpleList(req *GetGameSimpleListReq) (resp *GetGameSimpleListResp, err error) {
resp = CreateGetGameSimpleListResp()
err = c.DoAction(req, resp)
return
}
// GetGameServerV2 获取游戏服务器列表v2
func (c *Client) GetGameServerV2(req *GetServerV2Request) (resp *GetServerV2Response, err error) {
resp = CreateGetServerV2Response()
err = c.DoAction(req, resp)
return
}
// GetGameCompany 获取单个根游戏信息
func (c *Client) GetGameCompany(req *GetGameCompanyReq) (resp *GetGameCompanyResp, err error) {
resp = CreateGetGameCompanyResp()
err = c.DoAction(req, resp)
return
}
// GetIsBlockOutIos 获取iOS切支付规则
func (c *Client) GetIsBlockOutIos(req *IsBlockOutIosReq) (resp *IsBlockOutIosResp, err error) {
resp = CreateIsBlockOutIosResp()
err = c.DoAction(req, resp)
return
}
func (c *Client) GetGameVersion(req *GetGameVersionReq) (resp *GetGameVersionResp, err error) {
resp = CreateGetGameVersionResp()
err = c.DoAction(req, resp)
return
}
// GetConfig 获取游戏全局配置
func (c *Client) GetConfig(req *GetConfigReq) (resp *GetConfigResp, err error) {
resp = CreateGetConfigResp()
err = c.DoAction(req, resp)
return
}
// GetRealAuthBlackList 获取实名黑名单
func (c *Client) GetRealAuthBlackList(req *GetRealAuthBlackListReq) (resp *GetRealAuthBlackListResp, err error) {
resp = CreateGetRealAuthBlackListResp()
err = c.DoAction(req, resp)
return
}
// GetGameRealAuthInfo 获取实名参数
func (c *Client) GetGameRealAuthInfo(req *GetGameRealAuthInfoReq) (resp *GetGameRealAuthInfoResp, err error) {
resp = CreateGetGameRealAuthInfoResp()
err = c.DoAction(req, resp)
return
}
// GetProtocolByCompany 根据主体获取用户协议
func (c *Client) GetProtocolByCompany(req *GetProtocolByCompanyRep) (resp *GetProtocolByCompanyResp, err error) {
resp = CreateGetProtocolByCompanyResp()
err = c.DoAction(req, resp)
return
}
// KickUser 踢人
func (c *Client) KickUser(req *KickUserReq) (resp *KickUserResp, err error) {
resp = CreateKickUserResp()
err = c.DoAction(req, resp)
return
}

View File

@ -3,7 +3,6 @@ package game
import (
"fmt"
"testing"
"time"
)
func TestGetGameOsInfo(t *testing.T) {
@ -21,209 +20,3 @@ func TestGetGameOsInfo(t *testing.T) {
fmt.Println(resp.Code, resp.Msg, resp.Data.OsList, resp.Data.OsRelList2)
}
func TestGetGameInfo(t *testing.T) {
client, err := NewClient()
if err != nil {
panic(err)
}
resp, err := client.GetGameInfo(CreateGetGameInfoByIdReq(797, 1))
if err != nil {
panic(err)
}
fmt.Println(resp.Code, resp.Msg, resp.Data.GameHomeShortImage)
}
func TestChannelInfo(t *testing.T) {
client, err := NewClient()
if err != nil {
panic(err)
}
req := CreateChannelInfoReq()
req.ChannelKey = "GRSDK"
resp, err := client.GetChannelInfo(req)
if err != nil {
panic(err)
}
fmt.Println(resp)
}
func TestLoginInfoById(t *testing.T) {
client, err := NewClient()
if err != nil {
panic(err)
}
req := CreateGetLoginInfoByIdReq(7349, "1.0.0")
info, err := client.GetLoginInfoById(req)
if err != nil {
t.Error(err)
return
}
fmt.Println(info)
}
func TestGetProtocolByGameId(t *testing.T) {
client, err := NewClient()
if err != nil {
panic(err)
}
req := CreateGetProtocolByGameIdRep()
req.GameId = 8088
req.GameVersion = "1.1.0"
req.Type = 1
info, err := client.GetProtocolByGameId(req)
if err != nil {
t.Error(err)
return
}
fmt.Println(info)
}
func TestGetGameSimpleList(t *testing.T) {
client, err := NewClient()
if err != nil {
panic(err)
}
req := CreateGetGameSimpleListReq("8071,8062", "")
info, err := client.GetGameSimpleList(req)
if err != nil {
t.Error(err)
return
}
fmt.Println(info)
}
func TestGetGameServerV2(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
req := CreateGetServerV2Request("n2", "", "")
info, err := client.GetGameServerV2(req)
if err != nil {
t.Error(err)
return
}
fmt.Println(info)
}
func TestGetGameCompany(t *testing.T) {
client, err := NewClient()
if err != nil {
t.Error(err)
}
req := CreateGetGameCompanyReq("ascq")
gameCompany, err := client.GetGameCompany(req)
if err != nil {
t.Error(err)
return
}
fmt.Println(gameCompany)
fmt.Println(gameCompany.Data.System)
}
func TestIsBlockOutIos(t *testing.T) {
client, err := NewClient()
if err != nil {
t.Error(err)
}
isBlockOutIosReq := CreateIsBlockOutIosReq("ec63860282", 4570, "116.26.129.38", "", 0, 0)
isBlockOutIos, err := client.GetIsBlockOutIos(isBlockOutIosReq)
if err != nil {
t.Error(err)
return
}
t.Log(isBlockOutIos)
}
// 获取游戏全局配置
func TestGetConfig(t *testing.T) {
client, err := NewClient()
if err != nil {
t.Error(err)
}
getConfigReq := CreateGetConfigReq("overlord_act_config")
isBlockOutIos, err := client.GetConfig(getConfigReq)
if err != nil {
t.Error(err)
return
}
t.Log(isBlockOutIos)
}
// 获取实名黑名单
func TestGetRealAuthBlackList(t *testing.T) {
client, err := NewClient()
if err != nil {
t.Error(err)
}
getRealAuthBlackListReq := CreateGetRealAuthBlackListReq()
isBlockOutIos, err := client.GetRealAuthBlackList(getRealAuthBlackListReq)
if err != nil {
t.Error(err)
return
}
t.Log(isBlockOutIos)
}
// 获取游戏实名参数
func TestGetGameRealAuthInfo(t *testing.T) {
client, err := NewClient()
if err != nil {
t.Error(err)
}
getGameRealAuthInfoReq := CreateGetGameRealAuthInfoReq(7081)
isBlockOutIos, err := client.GetGameRealAuthInfo(getGameRealAuthInfoReq)
if err != nil {
t.Error(err)
return
}
t.Log(isBlockOutIos)
}
func TestGetGameVersion(t *testing.T) {
client, err := NewClient()
if err != nil {
t.Error(err)
return
}
req := CreateGetGameVersionReq(8071, "1.0.6")
resp, err := client.GetGameVersion(req)
if err != nil {
t.Error(err)
return
}
t.Log(resp)
}
func TestClient_GetProtocolByCompany(t *testing.T) {
client, err := NewClient()
if err != nil {
t.Error(err)
return
}
req := CreateGetProtocolByCompanyRep()
req.Company = "GR"
req.Type = 0
resp, err := client.GetProtocolByCompany(req)
if err != nil {
t.Error(err)
return
}
t.Log(resp.Code, resp.Msg, resp.Data.Content)
}
// 测试踢人
func TestKickUser(t *testing.T) {
client, err := NewClient()
if err != nil {
t.Error(err)
} // CreateKickUserReq
getRealAuthBlackListReq := CreateKickUserReq(8677, "wzcqtest", "8676", time.Now().Unix())
kickUserResp, err := client.KickUser(getRealAuthBlackListReq)
if err != nil {
t.Error(err)
return
}
t.Log(kickUserResp)
}

View File

@ -1,7 +1,6 @@
package game
import (
"fmt"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
)
@ -48,443 +47,3 @@ func CreateGetGameOsInfoResp() *GetGameOsInfoResp {
BaseResponse: &responses.BaseResponse{},
}
}
type GetGameInfoReq struct {
*requests.RpcRequest
}
type GetGameInfoResp struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data GameInfoData `json:"data"`
}
type GetGameInfoReqData struct {
GameId int
NoCache int
}
type GameInfoData struct {
AcceptRelatedGame int `json:"accept_related_game"`
ActCodeState int `json:"act_code_state"`
AgentSign string `json:"agent_sign"`
AppId string `json:"app_id"`
AppName string `json:"app_name"`
Autologin int `json:"autologin"`
BName string `json:"b_name"`
BackResult int `json:"back_result"`
BusinessPurpose int `json:"business_purpose"`
ChannelShow int `json:"channel_show"`
ClientType int `json:"client_type"`
Company string `json:"company"`
CreatedAt string `json:"created_at"`
CreatedRealname string `json:"created_realname"`
CreatedUsername string `json:"created_username"`
DisableBack int `json:"disable_back"`
DisablePay int `json:"disable_pay"`
DisableRegister int `json:"disable_register"`
DisableRelatedBack int `json:"disable_related_back"`
DisableUnrelatedLogin int `json:"disable_unrelated_login"`
Discount int `json:"discount"`
Divide int `json:"divide"`
DownloadDomain string `json:"download_domain"`
DownloadId string `json:"download_id"`
ExchangeRate int `json:"exchange_rate"`
ExtData string `json:"ext_data"`
Fcmathod int `json:"fcmathod"`
FirstLetter string `json:"first_letter"`
FlashAuthId string `json:"flash_auth_id"`
FlashAuthKey string `json:"flash_auth_key"`
FlashAuthLogo string `json:"flash_auth_logo"`
FlashAuthName string `json:"flash_auth_name"`
FlashAuthStatus int `json:"flash_auth_status"`
FlashPassId string `json:"flash_pass_id"`
FlashPassKey string `json:"flash_pass_key"`
GameByname string `json:"game_byname"`
GameIconImg string `json:"game_icon_img"`
GameImage string `json:"game_image"`
GameHomeImage string `json:"game_home_image"`
GameHomeShortImage string `json:"game_home_short_image"`
GameSign string `json:"game_sign"`
GameTsUrl string `json:"game_ts_url"`
GameVersion string `json:"game_version"`
GameZsUrl string `json:"game_zs_url"`
GetRoleUrl string `json:"get_role_url"`
HideRedButton int `json:"hide_red_button"`
Icon string `json:"icon"`
Icp string `json:"icp"`
IcpUrl string `json:"icp_url"`
Id int `json:"id"`
IsAugment int `json:"is_augment"`
IsOpen int `json:"is_open"`
IsSync int `json:"is_sync"`
MarketName string `json:"market_name"`
MediaAbbr string `json:"media_abbr"`
MobileLoginState int `json:"mobile_login_state"`
MobileRegState int `json:"mobile_reg_state"`
Name string `json:"name"`
ObjectiveId int `json:"objective_id"`
OpenGame int `json:"open_game"`
Os int `json:"os"`
OsTwo int `json:"os_two"`
Owner int `json:"owner"`
PackageNameId int `json:"package_name_id"`
PayUrl string `json:"pay_url"`
PlatId int `json:"plat_id"`
Platform int `json:"platform"`
ProtocolPreState int `json:"protocol_pre_state"`
Rank int `json:"rank"`
RegisterProtocolState int `json:"register_protocol_state"`
RelateGame string `json:"relate_game"`
ReleaseState int `json:"release_state"`
Remark string `json:"remark"`
RequestDomain string `json:"request_domain"`
ResultCode string `json:"result_code"`
ScreenType int `json:"screen_type"`
ServerGroupId int `json:"server_group_id"`
ServerSign int `json:"server_sign"`
SimId int `json:"sim_id"`
SpareRequestDomain string `json:"spare_request_domain"`
TwOs int `json:"tw_os"`
TwPlatId int `json:"tw_plat_id"`
UpdatedAt string `json:"updated_at"`
UpdatedRealname string `json:"updated_realname"`
UpdatedUsername string `json:"updated_username"`
IsAuth int `json:"is_auth"`
}
func CreateGetGameInfoByIdReq(gameId, noCache int) *GetGameInfoReq {
req := &GetGameInfoReq{
RpcRequest: &requests.RpcRequest{},
}
req.InitWithApiInfo(HOST, VERSION, fmt.Sprintf("/api/game/getGameById/%d?no_cache=%d", gameId, noCache))
req.Method = requests.GET
return req
}
func CreateGetGameInfoByIdResp() *GetGameInfoResp {
return &GetGameInfoResp{
BaseResponse: &responses.BaseResponse{},
}
}
type GetGameSimpleListReq struct {
*requests.RpcRequest
}
type GetGameSimpleListResp struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data map[string]GameSimple `json:"data"`
}
type GameSimple struct {
ID int `json:"id"`
Name string `json:"name"`
GameSign string `json:"game_sign"`
}
// CreateGetGameSimpleListReq
// gids 子游戏字符串多个子游戏id用英文逗号分割
// game_signs 根游戏标识字符串,多个标识用英文逗号分割
func CreateGetGameSimpleListReq(gameIds string, gameSigns string) *GetGameSimpleListReq {
req := &GetGameSimpleListReq{
RpcRequest: &requests.RpcRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/api/game/getSimpleList")
tmpParams := make(map[string]string)
if gameIds != "" {
tmpParams["gids"] = gameIds
}
if gameSigns != "" {
tmpParams["game_signs"] = gameSigns
}
req.FormParams = tmpParams
req.Method = requests.POST
return req
}
func CreateGetGameSimpleListResp() *GetGameSimpleListResp {
return &GetGameSimpleListResp{
BaseResponse: &responses.BaseResponse{},
}
}
// GameCompany
// ==== 获取根游戏信息
type GameCompany struct {
Id int `json:"id"`
GameSign string `json:"game_sign"`
Name string `json:"name"`
GameName string `json:"game_name"`
ContractName string `json:"contract_name"`
PayKey string `json:"pay_key"`
LoginKey string `json:"login_key"`
LoginUrlH5 string `json:"login_url_h5"`
LoginUrlIos string `json:"login_url_ios"`
LoginUrlAndroid string `json:"login_url_android"`
PayUrl string `json:"pay_url"`
Ext string `json:"ext"`
Status int `json:"status"`
Company string `json:"company"`
System string `json:"system"`
Sync int `json:"sync"`
Type int `json:"type"`
GameProductId int `json:"game_product_id"`
}
type GetGameCompanyReq struct {
*requests.RpcRequest
}
type GetGameCompanyResp struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data GameCompany `json:"data"`
}
func CreateGetGameCompanyReq(gameSign string) *GetGameCompanyReq {
req := &GetGameCompanyReq{
RpcRequest: &requests.RpcRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/api/game/getGameCompanyBySign")
req.FormParams = map[string]string{
"gameSign": gameSign,
}
req.Method = requests.POST
return req
}
func CreateGetGameCompanyResp() *GetGameCompanyResp {
return &GetGameCompanyResp{
BaseResponse: &responses.BaseResponse{},
}
}
// ==== 获取游戏客户端版本配置
type GameVersion struct {
ID int `json:"id"`
GameID int `json:"game_id"`
GameVersion string `json:"version"`
GameURL string `json:"url"`
PayCallbackURL string `json:"pay_callback_url"`
DomainURL string `json:"domain_url"`
Status int `json:"status"`
H5Version int `json:"h5_version"`
H5Status int `json:"h5_status"`
IsH5Logout int `json:"is_h5_logout"`
HideWindow int `json:"hidewindow"`
PayInfo PayInfo `json:"pay_display_info"`
IsYsdk int `json:"is_ysdk"`
CheckVerified int `json:"check_verified"`
Company string `json:"company"`
CompanyKf string `json:"company_kf"`
CompanyProto string `json:"company_proto"`
CompanySms string `json:"company_sms"`
KfStatus int `json:"kf_status"`
PopupTime int `json:"popup_time"`
ExtData map[string]any `json:"ext_data"`
VersionStatus int `json:"version_status"`
VersionTime int `json:"version_time"`
RequestDomain string `json:"request_domain"`
SpareRequestDomain string `json:"spare_request_domain"`
OtherRequestDomain string `json:"other_request_domain"`
}
type GetGameVersionReq struct {
*requests.RpcRequest
GameId int `position:"Body" field:"game_id"`
GameVersion string `position:"Body" field:"game_version"`
}
type GetGameVersionResp struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data GameVersion `json:"data"`
}
func CreateGetGameVersionReq(gameId int, gameVersion string) *GetGameVersionReq {
req := &GetGameVersionReq{
RpcRequest: &requests.RpcRequest{},
}
req.GameId = gameId
req.GameVersion = gameVersion
req.InitWithApiInfo(HOST, VERSION, "/api/game/getGameVersion")
req.Method = requests.POST
return req
}
func CreateGetGameVersionResp() *GetGameVersionResp {
return &GetGameVersionResp{
BaseResponse: &responses.BaseResponse{},
}
}
// GetConfigReq
// 游戏全局配置
type GetConfigReq struct {
*requests.RpcRequest
Key string `position:"Query" field:"key" default:"-" `
}
type GetConfigRespData struct {
Id int `json:"id"`
Key string `json:"key"`
ExtData string `json:"ext_data"`
}
type GetConfigResp struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data GetConfigRespData `json:"data"`
}
func CreateGetConfigReq(key string) *GetConfigReq {
req := &GetConfigReq{
RpcRequest: &requests.RpcRequest{},
}
req.Key = key
req.InitWithApiInfo(HOST, VERSION, "/api/game/getConfig")
req.Method = requests.GET
return req
}
func CreateGetConfigResp() *GetConfigResp {
return &GetConfigResp{
BaseResponse: &responses.BaseResponse{},
}
}
// GetRealAuthBlackListReq
// 获取实名黑名单
type GetRealAuthBlackListReq struct {
*requests.RpcRequest
Key string `position:"Query" field:"key" default:"-" `
}
type GetRealAuthBlackListRespDataItem struct {
Id int `json:"id"`
TrueName string `json:"true_name"`
IdCard string `json:"id_card"`
Remark string `json:"remark"`
CreateBy string `json:"create_by"`
UpdateBy string `json:"update_by"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
type GetRealAuthBlackListResp struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data []GetRealAuthBlackListRespDataItem `json:"data"`
}
func CreateGetRealAuthBlackListReq() *GetRealAuthBlackListReq {
req := &GetRealAuthBlackListReq{
RpcRequest: &requests.RpcRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/api/game/getRealAuthBlackList")
req.Method = requests.GET
return req
}
func CreateGetRealAuthBlackListResp() *GetRealAuthBlackListResp {
return &GetRealAuthBlackListResp{
BaseResponse: &responses.BaseResponse{},
}
}
// GetGameRealAuthInfoReq
// 获取实名参数
type GetGameRealAuthInfoReq struct {
*requests.RpcRequest
GameId int64 `position:"Body" field:"game_id" default:"-" `
}
type GetGameRealAuthInfoRespData struct {
GroupName string `json:"group_name"`
GroupDescription int `json:"group_description"`
VerifiedTime string `json:"verified_time"`
AreaProvince string `json:"area_province"`
VersionInfo string `json:"version_info"`
IsReal int `json:"is_real"`
IsDirect int `json:"is_direct"`
AuthChannel string `json:"auth_channel"`
StandbyAuthChannel string `json:"standby_auth_channel"`
ProtectTime int `json:"protect_time"`
GovIoReport int `json:"gov_io_report"`
MinorBan int `json:"minor_ban"`
}
type GetGameRealAuthInfoResp struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data GetGameRealAuthInfoRespData `json:"data"`
}
func CreateGetGameRealAuthInfoReq(gameId int64) *GetGameRealAuthInfoReq {
req := &GetGameRealAuthInfoReq{
RpcRequest: &requests.RpcRequest{},
GameId: gameId,
}
req.InitWithApiInfo(HOST, VERSION, "/api/login/getGameRealAuthInfo")
req.Method = requests.POST
return req
}
func CreateGetGameRealAuthInfoResp() *GetGameRealAuthInfoResp {
return &GetGameRealAuthInfoResp{
BaseResponse: &responses.BaseResponse{},
}
}
// KickUserReq
// 踢人下线
type KickUserReq struct {
*requests.RpcRequest
Uid int64 `position:"Body" field:"uid" default:"-" `
GameSign string `position:"Body" field:"game_sign" default:"-" `
ServerSign string `position:"Body" field:"server_sign" default:"-" `
Time int64 `position:"Body" field:"time" default:"-" `
}
type KickUserRespDataCallCpInfo struct {
Url string `json:"url"`
RequestParam map[string]any `json:"request_param"`
Response map[string]any `json:"response"`
}
type KickUserRespData struct {
CallCpInfo KickUserRespDataCallCpInfo `json:"call_cp_info"`
}
type KickUserResp struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data KickUserRespData `json:"data"`
}
func CreateKickUserReq(uid int64, gameSign string, serverSign string, time int64) *KickUserReq {
req := &KickUserReq{
RpcRequest: &requests.RpcRequest{},
Uid: uid,
GameSign: gameSign,
ServerSign: serverSign,
Time: time,
}
req.InitWithApiInfo(HOST, VERSION, "/api/game/kickUser")
req.Method = requests.POST
return req
}
func CreateKickUserResp() *KickUserResp {
return &KickUserResp{
BaseResponse: &responses.BaseResponse{},
}
}

View File

@ -1,107 +0,0 @@
package game
import (
"crypto/md5"
"encoding/hex"
"fmt"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
"time"
)
var (
gameServerKey = "gaoreapi"
)
// GetGameServerSign 子游戏区服信息,特有验签
func GetGameServerSign(gameId int) (ts int64, sign string) {
ts = time.Now().Unix()
hash := md5.New()
hash.Write([]byte(fmt.Sprintf("%v%v%v", gameId, ts, gameServerKey)))
hashBytes := hash.Sum(nil)
sign = hex.EncodeToString(hashBytes)
return
}
type GetServerIdRequest struct {
*requests.RpcRequest
}
type GetServerIdResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data map[string]string `json:"data"`
}
// CreateGetServerIdRequest
// Deprecated 方法已废弃,不要用
func CreateGetServerIdRequest(gameId int) (req *GetServerIdRequest) {
req = &GetServerIdRequest{
RpcRequest: &requests.RpcRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/api/game/getServerId")
// 获取时间戳、签名
ts, sign := GetGameServerSign(gameId)
req.FormParams = map[string]string{
"appid": fmt.Sprintf("%v", gameId),
"time": fmt.Sprintf("%v", ts),
"sign": sign,
}
req.Method = requests.POST
return
}
// CreateGetServerIdResponse
// Deprecated 方法已废弃,不要用
func CreateGetServerIdResponse() (response *GetServerIdResponse) {
response = &GetServerIdResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}
// --------------游戏区服v2列表查询----------
// GetServerV2Request 请求结构体
type GetServerV2Request struct {
*requests.RpcRequest
}
type GetServerV2Response struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data []GameServerV2 `json:"data"`
}
type GameServerV2 struct {
ServerId int `json:"server_id"`
Name string `json:"name"`
GameSign string `json:"game_sign"`
ServerSign int `json:"server_sign"`
}
func CreateGetServerV2Request(gameSign string, serverSigns string, types string) (req *GetServerV2Request) {
req = &GetServerV2Request{
RpcRequest: &requests.RpcRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/api/game/getServerV2")
req.FormParams = map[string]string{
"game_sign": gameSign,
"server_signs": serverSigns,
"types": types,
}
req.Method = requests.POST
return
}
func CreateGetServerV2Response() (response *GetServerV2Response) {
response = &GetServerV2Response{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -1,73 +0,0 @@
package game
import (
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
)
type GetLoginInfoByIdReq struct {
*requests.RpcRequest
GameId int `position:"Body" field:"game_id"`
GameVersion string `position:"Body" field:"game_version"`
Uid int `position:"Body" field:"uid"`
UserName string `position:"Body" field:"uname"`
}
type PayInfo struct {
HiddenAlipay int `json:"hide_alipay"`
HiddenWx int `json:"hide_wx"`
HiddenUnionPay int `json:"hide_union_pay"`
}
type GameVersionInfo struct {
AppName string `json:"app_name"`
AppID string `json:"app_id"`
LoginURL string `json:"login_url"`
PayURL string `json:"pay_url"`
GameURL string `json:"game_url"`
PayCallbackURL string `json:"pay_callback_url"`
IsH5Logout int `json:"is_h5_logout"`
HideWindow int `json:"hidewindow"`
GameVersion string `json:"version"`
GameSign string `json:"game_sign"`
GameSignName string `json:"game_sign_name"`
GameSignID int `json:"game_sign_id"`
IsYsdk int `json:"is_ysdk"`
Company string `json:"company"`
CompanyKf string `json:"company_kf"`
CompanyProto string `json:"company_proto"`
CompanySms string `json:"company_sms"`
KfStatus int `json:"kf_status"`
PopupTime int `json:"popup_time"`
GameId int `json:"game_id"`
ScreenType int `json:"screen_type"`
GameSwitch int `json:"game_switch"` // 根据上下文0 或 1 的整数表示布尔值
ExtData map[string]any `json:"ext_data"`
OsName string `json:"os_name"`
PayInfo PayInfo `json:"pay_info"`
}
type GetLoginInfoByIdResp struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data GameVersionInfo `json:"data"`
}
func CreateGetLoginInfoByIdReq(gameId int, gameVersion string) *GetLoginInfoByIdReq {
req := &GetLoginInfoByIdReq{
RpcRequest: &requests.RpcRequest{},
}
req.GameId = gameId
req.GameVersion = gameVersion
req.InitWithApiInfo(HOST, VERSION, "/api/login/getInfoById")
req.Method = requests.POST
return req
}
func CreateGetLoginInfoByIdResp() *GetLoginInfoByIdResp {
resp := &GetLoginInfoByIdResp{
BaseResponse: &responses.BaseResponse{},
}
return resp
}

View File

@ -1,67 +0,0 @@
package game
import (
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
)
type GetProtocolByGameIdRep struct {
*requests.RpcRequest
GameId int `position:"Query" field:"game_id"`
GameVersion string `position:"Query" field:"game_version"`
Type int `position:"Query" field:"type"`
}
type GetProtocolByGameIdResp struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
Content string `json:"content"`
} `json:"data"`
}
func CreateGetProtocolByGameIdRep() *GetProtocolByGameIdRep {
req := &GetProtocolByGameIdRep{
RpcRequest: &requests.RpcRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/api/news/getProtocolByGameId")
req.Method = requests.GET
return req
}
func CreateGetProtocolByGameIdResp() *GetProtocolByGameIdResp {
return &GetProtocolByGameIdResp{
BaseResponse: &responses.BaseResponse{},
}
}
type GetProtocolByCompanyRep struct {
*requests.RpcRequest
Company string `position:"Query" field:"company"`
Type int `position:"Query" field:"type"`
}
type GetProtocolByCompanyResp struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
Content string `json:"content"`
} `json:"data"`
}
func CreateGetProtocolByCompanyRep() *GetProtocolByCompanyRep {
req := &GetProtocolByCompanyRep{
RpcRequest: &requests.RpcRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/api/news/getProtocolByCompany")
req.Method = requests.GET
return req
}
func CreateGetProtocolByCompanyResp() *GetProtocolByCompanyResp {
return &GetProtocolByCompanyResp{
BaseResponse: &responses.BaseResponse{},
}
}

View File

@ -1,60 +0,0 @@
package game
import (
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
)
// IsBlockOutIosReq
// 获取切支付规则
type IsBlockOutIosReq struct {
*requests.RpcRequest
UserName string `position:"Body" field:"user_name"`
GameId int64 `position:"Body" field:"appid"`
Ip string `position:"Body" field:"ip"`
Imei string `position:"Body" field:"imei"`
LoginDays int64 `position:"Body" field:"login_days"`
PlayTime int64 `position:"Body" field:"play_time"`
}
type IsBlockOutIosRespData struct {
PayInChannel bool `json:"pay_in_channel"`
PayInChannelMatchedRule []int64 `json:"pay_in_channel_matched_rule"`
DoDisplayIos bool `json:"do_display_ios"`
DoDisplayIosMatchedRule []int64 `json:"do_display_ios_matched_rule"`
DoDisplayWebsite bool `json:"do_display_website"`
DoDisplayWebsiteMatchedRule []int64 `json:"do_display_website_matched_rule"`
DoDisplayWebsiteWechatInfo string `json:"do_display_website_wechat_info"`
DoWebOrderPay bool `json:"do_web_order_pay"`
DoWebOrderPayMatchedRule []int64 `json:"do_web_order_pay_matched_rule"`
DoWebOrderPayWechatInfo string `json:"do_web_order_pay_wechat_info"`
}
type IsBlockOutIosResp struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data IsBlockOutIosRespData `json:"data"`
}
func CreateIsBlockOutIosReq(userName string, gameId int64, ip string, imei string, loginDays, playTime int64) *IsBlockOutIosReq {
req := &IsBlockOutIosReq{
RpcRequest: &requests.RpcRequest{},
}
req.UserName = userName
req.GameId = gameId
req.Ip = ip
req.Imei = imei
req.LoginDays = loginDays
req.PlayTime = playTime
req.InitWithApiInfo(HOST, VERSION, "/api/pay/isBlockOutIos")
req.Method = requests.POST
return req
}
func CreateIsBlockOutIosResp() *IsBlockOutIosResp {
resp := &IsBlockOutIosResp{
BaseResponse: &responses.BaseResponse{},
}
return resp
}

View File

@ -1,36 +0,0 @@
package ip
import (
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
)
const (
VERSION = "2025-06-24"
)
var HOST = requests.Host{
Default: "ip",
}
type Client struct {
sdk.Client
}
func NewClient() (client *Client, err error) {
client = new(Client)
err = client.Init()
return
}
func (client *Client) CreateGetIpRequest(req *IpRequest) (resp *IpResponse, err error) {
resp = CreateIpResponse()
err = client.DoAction(req, resp)
return
}
func (client *Client) CreateGetIpsRequest(req *IpsRequest) (resp *IpsResponse, err error) {
resp = CreateIpsResponse()
err = client.DoAction(req, resp)
return
}

View File

@ -1,48 +0,0 @@
package ip
import (
"fmt"
"testing"
)
// 测试获取单个ip地区信息
func TestGetIp(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
req := CreateIpRequest(IpParam{
Ip: "114.234.202.136",
})
res, doErr := client.CreateGetIpRequest(req)
if doErr != nil {
panic(doErr)
}
if res.Code != 0 {
t.Error("查询多个ip失败")
}
fmt.Printf(fmt.Sprintf("%v", res))
}
// 测试获取多个ip地区信息
func TestGetIps(t *testing.T) {
client, newErr := NewClient()
if newErr != nil {
panic(newErr)
}
req := CreateIpsRequest(IpsParam{
Ips: []string{
"2001:ee0:5208:e600:4c51:3189:28a4:b668",
"114.234.202.136",
},
})
res, err := client.CreateGetIpsRequest(req)
if err != nil {
t.Error(err)
return
}
if res.Code != 0 {
t.Error("查询多个ip失败")
}
fmt.Printf(fmt.Sprintf("%v", res))
}

View File

@ -1,100 +0,0 @@
package ip
import (
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
)
type IpInfo struct {
Ip string `json:"ip"`
City string `json:"city"`
Province string `json:"province"`
Country string `json:"country"`
Isp string `json:"isp"`
Owner string `json:"owner"`
Continent string `json:"continent"`
Accuracy string `json:"accuracy"`
Adcode string `json:"adcode"`
Areacode string `json:"areacode"`
Asnumber string `json:"asnumber"`
Radius string `json:"radius"`
Latwgs string `json:"latwgs"`
Lngwgs string `json:"lngwgs"`
Source string `json:"source"`
Timezone string `json:"timezone"`
Zipcode string `json:"zipcode"`
District string `json:"district"`
}
// IpsParam
// 单个ip请求参数
type IpParam struct {
Ip string `json:"ip"`
}
type IpRequest struct {
*requests.JsonRequest
Ip string `position:"Json" field:"ip"`
}
// IpResponse
// 单个ip返回参数
type IpResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data IpInfo `json:"data"`
}
// CreateIpRequest
// 同时支持ipv4、ipv6格式查询
func CreateIpRequest(param IpParam) (req *IpRequest) {
req = &IpRequest{
JsonRequest: &requests.JsonRequest{},
Ip: param.Ip,
}
req.InitWithApiInfo(HOST, VERSION, "/v1/getIp")
req.Method = requests.POST
return
}
func CreateIpResponse() (resp *IpResponse) {
resp = &IpResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}
// 多个ip请求参数
type IpsParam struct {
Ips []string `json:"ips"`
}
type IpsRequest struct {
*requests.JsonRequest
Ips []string `position:"Json" field:"ips"`
}
// IpsResponse
// 多个ip返回参数
type IpsResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data map[string]IpInfo `json:"data"`
}
// CreateIpsRequest
// 同时支持ipv4、ipv6格式查询
func CreateIpsRequest(param IpsParam) (req *IpsRequest) {
req = &IpsRequest{
JsonRequest: &requests.JsonRequest{},
Ips: param.Ips,
}
req.InitWithApiInfo(HOST, VERSION, "/v1/getIps")
req.Method = requests.POST
return
}
func CreateIpsResponse() (resp *IpsResponse) {
resp = &IpsResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -1,7 +1,6 @@
package mkt
import (
"encoding/json"
"fmt"
"testing"
)
@ -19,11 +18,5 @@ func TestSubjectList(t *testing.T) {
panic(err)
}
marshal, err := json.Marshal(list.Data)
if err != nil {
panic(err)
}
fmt.Println(string(marshal))
fmt.Println(list.Status, list.Code, list.Msg, list.Data)
}

View File

@ -33,7 +33,6 @@ type Data struct {
State int `json:"state"`
System string `json:"system"`
Type int `json:"type"`
Uscc string `json:"uscc"`
}
// CreateSubjectListRequest 公司列表请求

View File

@ -1,61 +0,0 @@
package msdk
import (
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
)
const VERSION = "2024-06-25"
var HOST = requests.Host{
Default: "msdk.api.gaore.com",
}
type Client struct {
sdk.Client
}
func NewClient() (client *Client, err error) {
client = &Client{}
err = client.Init()
return
}
// GetIdfa 获取设备归因信息
func (c *Client) GetIdfa(req *GetIdfaReq) (resp *GetIdfaResp, err error) {
resp = &GetIdfaResp{
BaseResponse: &responses.BaseResponse{},
}
if req.Imei == "" && req.Idfa != "" {
req.Imei = req.Idfa
}
err = c.DoAction(req, resp)
return
}
// GetUserAttr 获取用户归因信息
func (c *Client) GetUserAttr(req *GetUserAttrReq) (resp *GetUserAttrResp, err error) {
resp = &GetUserAttrResp{
BaseResponse: &responses.BaseResponse{},
}
err = c.DoAction(req, resp)
return
}
// GetImei 用户注册归因
func (c *Client) GetImei(req *GetImeiReq) (resp *GetImeiResp, err error) {
resp = &GetImeiResp{
BaseResponse: &responses.BaseResponse{},
}
err = c.DoAction(req, resp)
return
}
func (c *Client) SetImei(req *SetImeiReq) (resp *SetImeiResp, err error) {
resp = &SetImeiResp{
BaseResponse: &responses.BaseResponse{},
}
err = c.DoAction(req, resp)
return
}

View File

@ -1,149 +0,0 @@
package msdk
import (
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/utils"
"testing"
)
func TestClient_GetUserAttr(t *testing.T) {
client, err := NewClient()
if err != nil {
t.Error(err)
return
}
req := CreateGetUserAttrReq("ql83649336", "xxhbbxxl")
resp, err := client.GetUserAttr(req)
if err != nil {
t.Error(err)
return
}
t.Log(resp)
}
func TestGetIdfa(t *testing.T) {
header := &requests.RefererHeader{
Referer: "https://www.gaore.com",
TraceId: utils.MakeTraceId(),
}
_ = header
client, err := NewClient()
if err != nil {
t.Error(err)
return
}
client.SetRefererHeader(header)
req := CreateGetIdfaReq()
req.ChannelId = 1
req.GameId = 3706
req.Ip = "112.23.230.210"
req.Imei = "00000000-0000-0000-0000-000000000000"
req.LongId = "daff65f07c7cf84862f4217773e3d613"
req.SdkVersion = "1.7.2"
req.Os = "ios"
req.GameOs = 2
req.GameSubOs = 0
req.Ua = "Mozilla/5.0 (iPad; CPU OS 15_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148"
req.GameSign = "hlhj"
req.PkgAgentId = "100"
req.PkgSiteId = "1001"
req.Network = "Wifi"
req.Idfv = "53F2A5F7-B1D4-4716-9775-07727C29BC7A"
req.ScreenResolution = "2360*1640"
req.System = "15.6.1"
req.ProcessorModel = "iPad13,16"
req.BaseBand = ""
req.Model = "iPad13,16"
req.Battery = "74"
req.Oaid = ""
req.AdInfo = ""
req.WxPlatform = ""
req.AdDevice = "{\"bootTimeInSec\":\"1745364499\",\"countryCode\":\"CN\",\"language\":\"zh-Hans-CN\",\"deviceName\":\"1b9018182a49e16ba85bb095f224867c\",\"systemVersion\":\"15.6.1\",\"machine\":\"iPad13,16\",\"carrierInfo\":\"unknown\",\"memory\":\"8000356352\",\"disk\":\"255983177728\",\"sysFileTime\":\"1663537105.729985\",\"model\":\"J407AP\",\"timeZone\":\"28800\",\"mntId\":\"A058368B97B0D073829608AAC13FFA64D9BEFD0FE3E14EDB106F2BABD6DF94B1C2BFC7509CBB683EE5B22D91A19FF67A@/dev/disk0s1s1\",\"deviceInitTime\":\"1663537056.906820124\"}"
resp, err := client.GetIdfa(req)
if err != nil {
t.Error(err)
return
}
t.Log(resp)
}
func TestGetImei(t *testing.T) {
client, err := NewClient()
if err != nil {
t.Error(err)
return
}
req := CreateGetImeiReq()
req.Uid = 218047048
req.UserName = "ct939725671"
req.GameId = 8050
req.GameSign = "mrwld"
req.RegTime = 1750939725
req.Imei = "of5wO5sKWep0OFPt9rWQf6xNJVPg"
req.ChannelId = 1
req.AgentId = 100
req.SiteId = 1001
req.Ip = "1864204063"
req.Idfa = "of5wO5sKWep0OFPt9rWQf6xNJVPg"
req.Logined = 1
req.MatchType = 1
req.GameAwemeId = ""
req.ComeBackUser = 0
req.FanCode = ""
req.Network = ""
req.Idfv = ""
req.ScreenResolution = ""
req.System = ""
req.Electric = ""
req.ProcessorModel = ""
req.BaseBand = ""
req.Model = ""
req.Battery = ""
req.Oaid = ""
req.AdInfo = ""
req.AdDevice = ""
req.Ua = "WebSdk GaoreGame/1.3.1"
req.WxPlatform = ""
resp, err := client.GetImei(req)
if err != nil {
t.Error(err)
}
t.Log(resp)
}
func TestSetImei(t *testing.T) {
client, err := NewClient()
if err != nil {
t.Error(err)
return
}
req := CreateSetImeiReq()
// 基础字段赋值
req.UserName = "15179405888"
req.GameId = 6062
req.GameSign = "hlhj"
req.ChannelId = 1 // mtype
req.MatchType = 2
req.Imei = "96d9acdd57535c92-null"
req.Idfa = "96d9acdd57535c92-null"
req.Network = "4G"
req.Idfv = ""
req.ScreenResolution = "2132x1080"
req.System = "11"
req.ProcessorModel = ""
req.BaseBand = ""
req.Model = "PCDM10"
req.Battery = "45"
req.Oaid = "B9258E43A5084B43B72D94580C830898343a97328d6fd210b9e23859b1d5e83d_gaore_"
req.AdInfo = ""
req.AdDevice = ""
req.Ua = "Mozilla/5.0 (Linux; Android 11; PCDM10 Build/RP1A.200720.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/83.0.4103.106 Mobile Safari/537.36; SHGR GaoreGame/2.3.5"
req.WxPlatform = ""
resp, err := client.SetImei(req)
if err != nil {
t.Error(err)
return
}
t.Log(resp)
}

View File

@ -1,218 +0,0 @@
package msdk
import (
"fmt"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/utils"
"time"
)
const msdkKey = "msdk@gaore.com#!!"
type GetIdfaReq struct {
*requests.RpcRequest
ChannelId int `position:"Query" field:"mtype"`
GameId int `position:"Query" field:"game_id"`
GameSign string `position:"Query" field:"game_sign"`
Ip string `position:"Query" field:"ip"`
Imei string `position:"Query" field:"imei"`
Idfa string `position:"Query" field:"idfa"`
Idfv string `position:"Query" field:"idfv"`
LongId string `position:"Query" field:"long_id"`
SdkVersion string `position:"Query" field:"version"`
Os string `position:"Query" field:"os"`
GameOs int `position:"Query" field:"game_os"`
GameSubOs int `position:"Query" field:"game_sub_os"`
UserName string `position:"Query" field:"user_name"`
Ua string `position:"Query" field:"ua"`
LiveCode string `position:"Query" field:"live_code"`
AdDevice string `position:"Query" field:"ad_device"`
PkgAgentId string `position:"Query" field:"pkg_agent_id"`
PkgSiteId string `position:"Query" field:"pkg_site_id"`
Network string `position:"Query" field:"network"`
ScreenResolution string `position:"Query" field:"screen_resolution"`
System string `position:"Query" field:"system"`
Electric string `position:"Query" field:"electric"`
ProcessorModel string `position:"Query" field:"processor_model"`
BaseBand string `position:"Query" field:"baseband"`
Model string `position:"Query" field:"model"`
Battery string `position:"Query" field:"battery"`
Oaid string `position:"Query" field:"oaid"`
AdInfo string `position:"Query" field:"adinfo"`
WxPlatform string `position:"Query" field:"wx_platform"`
}
type GetIdfaResp struct {
*responses.BaseResponse
GameId int `json:"game_id"`
AgentId int `json:"agent_id"`
SiteId int `json:"site_id"`
GameAwemeId string `json:"game_aweme_id"`
LongId string `json:"long_id"`
DeviceId string `json:"device_id"`
Exists bool `json:"exists"`
FromAd bool `json:"from_ad"`
MatchType int `json:"match_type"`
ClickId string `json:"click_id,omitempty"` // 非必要字段,使用 omitempty 忽略空值
MatchTrace string `json:"match_trace,omitempty"` // 非必要字段
RegTime int64 `json:"reg_time"`
}
func CreateGetIdfaReq() *GetIdfaReq {
req := &GetIdfaReq{
RpcRequest: &requests.RpcRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/getidfa.php")
req.Method = requests.GET
return req
}
type GetUserAttrReq struct {
*requests.RpcRequest
UserName string `position:"Query" field:"user_name"`
GameSign string `position:"Query" field:"game_sign"`
Ts int64 `position:"Query" field:"ts"`
Sign string `position:"Query" field:"sign"`
}
type GetUserAttrResp struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
Uid int `json:"uid"`
UserName string `json:"user_name"`
RegTime int `json:"reg_time"` // 假设注册时间是时间戳
GameID int `json:"game_id"`
RegIP string `json:"reg_ip"`
AgentId int `json:"agent_id"`
SiteId int `json:"site_id"`
Imei string `json:"imei"`
Oaid string `json:"oaid"`
LongId string `json:"long_id"`
PromotionId string `json:"promotion_id"`
Mid3 string `json:"mid3"`
} `json:"data"`
}
func CreateGetUserAttrReq(userName, gameSign string) *GetUserAttrReq {
req := &GetUserAttrReq{
RpcRequest: &requests.RpcRequest{},
}
req.UserName = userName
req.GameSign = gameSign
req.Ts = time.Now().Unix()
req.Sign = utils.Md5(fmt.Sprintf("%d%s", req.Ts, msdkKey))
req.InitWithApiInfo(HOST, VERSION, "/getUserAttr.php")
req.Method = requests.GET
return req
}
type GetImeiReq struct {
*requests.RpcRequest
Uid int `position:"Query" field:"uid"`
UserName string `position:"Query" field:"user_name"`
GameId int `position:"Query" field:"game_id"`
GameSign string `position:"Query" field:"game_sign"`
RegTime int64 `position:"Query" field:"reg_time"`
Imei string `position:"Query" field:"imei"`
ChannelId int `position:"Query" field:"mtype"`
AgentId int `position:"Query" field:"agent_id"`
SiteId int `position:"Query" field:"site_id"`
Ip string `position:"Query" field:"ip"`
UserIp string `position:"Query" field:"user_ip"`
Idfa string `position:"Query" field:"idfa"`
Logined int `position:"Query" field:"logined"`
MatchType int `position:"Query" field:"match_type"`
GameAwemeId string `position:"Query" field:"game_aweme_id"`
ComeBackUser int `position:"Query" field:"come_back_user"` //回流用户标识 1=>回流用户
LpReg int `position:"Query" field:"lp_reg"` // 落地页注册用户标识
FanCode string `position:"Query" field:"fan_code"` // 粉丝码
Network string `position:"Query" field:"network"`
Idfv string `position:"Query" field:"idfv"`
ScreenResolution string `position:"Query" field:"screen_resolution"`
System string `position:"Query" field:"system"`
Electric string `position:"Query" field:"electric"`
ProcessorModel string `position:"Query" field:"processor_model"`
BaseBand string `position:"Query" field:"baseband"`
Model string `position:"Query" field:"model"`
Battery string `position:"Query" field:"battery"`
Oaid string `position:"Query" field:"oaid"`
AdInfo string `position:"Query" field:"adinfo"`
AdDevice string `position:"Query" field:"ad_device"`
Ua string `position:"Query" field:"ua"`
WxPlatform string `position:"Query" field:"wx_platform"`
}
type GetImeiResp struct {
*responses.BaseResponse
Uid string `json:"uid"`
UserName string `json:"user_name"`
Openid string `json:"openid"`
ChannelId string `json:"mtype"`
Logined int `json:"logined"`
GameId string `json:"game_id"`
GameSign string `json:"game_sign"`
MatchType int `json:"match_type"`
RegTime int64 `json:"reg_time"` // 原始时间戳字符串
Imei string `json:"imei"`
Oaid string `json:"oaid"`
Idfa string `json:"idfa"`
Ip int64 `json:"ip"`
UserIp string `json:"user_ip"`
Ua string `json:"ua"`
Media string `json:"media"`
AgentId int `json:"agent_id"`
SiteId int `json:"site_id"`
AdInfo string `json:"adinfo"`
GameAwemeId string `json:"game_aweme_id"`
}
func CreateGetImeiReq() *GetImeiReq {
req := &GetImeiReq{
RpcRequest: &requests.RpcRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/getimei.php")
req.Method = requests.GET
return req
}
type SetImeiReq struct {
*requests.RpcRequest
UserName string `position:"Query" field:"user_name"`
GameId int `position:"Query" field:"game_id"`
Imei string `position:"Query" field:"imei"`
Idfa string `position:"Query" field:"idfa"`
GameSign string `position:"Query" field:"game_sign"`
ChannelId int `position:"Query" field:"mtype"`
MatchType int `position:"Query" field:"match_type"`
Network string `position:"Query" field:"network"`
Idfv string `position:"Query" field:"idfv"`
ScreenResolution string `position:"Query" field:"screen_resolution"`
System string `position:"Query" field:"system"` // 可能为系统版本号字符串
ProcessorModel string `position:"Query" field:"processor_model"`
BaseBand string `position:"Query" field:"baseband"`
Model string `position:"Query" field:"model"`
Battery string `position:"Query" field:"battery"`
Oaid string `position:"Query" field:"oaid"`
AdInfo string `position:"Query" field:"adinfo"`
AdDevice string `position:"Query" field:"ad_device"`
Ua string `position:"Query" field:"ua"`
WxPlatform string `position:"Query" field:"wx_platform"`
}
type SetImeiResp struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
}
func CreateSetImeiReq() *SetImeiReq {
req := &SetImeiReq{
RpcRequest: &requests.RpcRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/setimei.php")
req.Method = requests.GET
return req
}

View File

@ -3,7 +3,6 @@ package oss
import (
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
"time"
)
type GetApkVersionRequest struct {
@ -29,7 +28,6 @@ func CreateGetApkVersionRequest() (req *GetApkVersionRequest) {
}
req.InitWithApiInfo(HOST, VERSION, "/api/apk/version")
req.Method = requests.POST
req.SetReadTimeout(30 * time.Second)
return
}

View File

@ -31,7 +31,7 @@ func NewClientWithSts() {
}
func (c *Client) PutOss(req *PutOssRequest) (resp *PutOssResponse, err error) {
if req.Bucket == "" {
if req.BucketName == "" {
err = errors.New("bucket name is empty")
return
}

View File

@ -8,8 +8,7 @@ import (
func TestUpload_Put(t *testing.T) {
req := CreatePutOssRequest()
req.Bucket = "image"
//req.Bucket = "web"
req.BucketName = "image"
file, err := os.ReadFile("test.jpg")
if err != nil {
t.Error(err)
@ -27,7 +26,7 @@ func TestUpload_Put(t *testing.T) {
func TestUpload_Del(t *testing.T) {
req := CreateDelOssRequest()
req.Bucket = "image"
req.BucketName = "image"
req.MediaUrl = "https://image.89yoo.com/uploads/549/549e887460a72333c361661683023018.jpeg"
client, err := NewClient()
if err != nil {
@ -73,7 +72,7 @@ func TestCreateInitMultipartUpload(t *testing.T) {
func TestClient_GetApkVersion(t *testing.T) {
req := CreateGetApkVersionRequest()
req.Filepath = "uploads/files/package/1f57ac9693f0593fc9073f366b1c1936.zip"
req.Filepath = "51c68615b8d21f9b72b02f48c400cb87.zip"
client, err := NewClient()
if err != nil {
t.Error(err)

View File

@ -7,8 +7,8 @@ import (
type DelOssRequest struct {
*requests.JsonRequest
Bucket string `position:"Json" field:"bucket" default:"image"`
MediaUrl string `position:"Json" field:"url" default:"-"`
BucketName string `position:"Json" field:"bucket_name" default:"image"`
MediaUrl string `position:"Json" field:"url" default:"-"`
}
type DelOssResponse struct {

View File

@ -7,7 +7,7 @@ import (
type PutOssRequest struct {
*requests.StreamRequest
Bucket string `position:"Query" field:"bucket" default:"image"`
BucketName string `position:"Query" field:"bucket_name" default:"image"`
FileStream []byte
}
@ -16,8 +16,7 @@ type PutOssResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
Url string `json:"url"`
SavePath string `json:"save_path"`
Url string `json:"url"`
}
}

View File

@ -1,81 +0,0 @@
package passport
import (
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"strings"
)
const (
VERSION = "2025-05-28"
// 对称加密密钥
appKey = "#gr*%com#"
)
var HOST requests.Host = requests.Host{
Default: "passport.gaore.com",
}
type Client struct {
sdk.Client
}
func NewClient() (client *Client, err error) {
client = new(Client)
err = client.Init()
return
}
// GetUserList
// 获取用户列表
func (c *Client) GetUserList(req *GetUserListRequest) (response *GetUserListResponse, err error) {
response = CreateGetUserListResponse()
err = c.DoAction(req, response)
return
}
// GetUserRoleList
// 获取用户角色列表
func (c *Client) GetUserRoleList(req *GetUserRoleListRequest) (response *GetUserRoleListResponse, err error) {
response = CreateGetUserRoleListResponse()
err = c.DoAction(req, response)
return
}
// EditCard
// 新增或修改实名信息
func (c *Client) EditCard(req EditCardRequestParam) (response string, err error) {
editCardRequest := CreateEditCardRequest(req)
createEditCardResponse := CreateEditCardResponse()
err = c.DoAction(editCardRequest, createEditCardResponse)
if err != nil && strings.Contains(err.Error(), "json Unmarshal:") {
return createEditCardResponse.GetHttpContentString(), nil
} else if err != nil {
return "", err
}
return createEditCardResponse.GetHttpContentString(), nil
}
// GetUserGameSign
// 获取用户登录过的游戏大类
func (c *Client) GetUserGameSign(req *GetUserGameSignRequest) (response *GetUserGameSignResponse, err error) {
response = CreateGetUserGameSignResponse()
err = c.DoAction(req, response)
return
}
// ChangePassword
// 用户修改密码
func (c *Client) ChangePassword(req *ChangePasswordRequest) (response *ChangePasswordResponse, err error) {
response = CreateChangePasswordResponse()
err = c.DoAction(req, response)
return
}
// UpdateUserState
// 修改用户状态
func (c *Client) UpdateUserState(req *UpdateUserStateRequest) (response *UpdateUserStateResponse, err error) {
response = CreateUpdateUserStateResponse()
err = c.DoAction(req, response)
return
}

View File

@ -1,111 +0,0 @@
package passport
import (
"testing"
)
// 单元测试
func TestGetUserList(t *testing.T) {
client, err := NewClient()
if err != nil {
t.Error(err)
}
req := CreateGetUserListRequest("ws45265737")
resp, err := client.GetUserList(req)
if err != nil {
t.Error(err)
}
t.Logf("resp code:%+v", resp.Code)
t.Logf("resp data:%+v", resp.Data)
}
func TestGetUserRoleList(t *testing.T) {
client, err := NewClient()
if err != nil {
t.Error(err)
}
// 不限定角色
//req := CreateGetUserRoleListRequest(221016372, 7874, 0, "")
// 限定角色
req := CreateGetUserRoleListRequest(221016372, 7874, 265500390, "勇闯关东")
resp, err := client.GetUserRoleList(req)
if err != nil {
t.Error(err)
}
t.Logf("resp code:%+v", resp.Code)
t.Logf("resp data:%+v", resp.Data)
}
func TestEditCard(t *testing.T) {
client, err := NewClient()
if err != nil {
t.Error(err)
}
editCardRequest := EditCardRequestParam{
Uid: 32455414,
GameId: 5010,
Imei: "11111111",
IsReal: 0,
DirectStatus: 1,
AuthChannel: "gjfcm_wzcq",
DirectExtData: "测试测试测试",
Pi: "",
Ip: "",
Ipv6: "",
UserName: "asfasfd",
RealName: "这艘啊",
IdCard: "33032419950123532X",
Mandatory: "3123123123",
}
editCardResponse, err := client.EditCard(editCardRequest)
t.Logf("%v", editCardResponse)
}
// 测试获取用户登录过的游戏大类
func TestGetUserGameSign(t *testing.T) {
client, err := NewClient()
if err != nil {
t.Error(err)
}
req := CreateGetUserGameSignRequest("oo70683572", "", "")
resp, err := client.GetUserGameSign(req)
if err != nil {
t.Error(err)
}
t.Logf("resp code:%+v", resp.Code)
t.Logf("resp data:%+v", resp.Data)
}
// 测试用户修改密码
func TestChangePassword(t *testing.T) {
client, err := NewClient()
if err != nil {
t.Error(err)
}
req := CreateChangePasswordRequest("rz35990497", "7654321")
resp, err := client.ChangePassword(req)
if err != nil {
t.Error(err)
}
// 记录文本结果
t.Logf("resp code:%+v, msg:%s", resp.Code, resp.Msg)
}
// 测试修改用户状态
func TestUpdateUserState(t *testing.T) {
client, err := NewClient()
if err != nil {
t.Error(err)
}
req := CreateUpdateUserStateRequest("masterpan", 0, 2)
resp, err := client.UpdateUserState(req)
if err != nil {
t.Error(err)
}
// 记录文本结果
t.Logf("resp code:%+v, msg:%s", resp.Code, resp.Msg)
}

View File

@ -1,43 +0,0 @@
package passport
import (
"fmt"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
)
type ChangePasswordRequest struct {
*requests.RpcRequest
}
func CreateChangePasswordRequest(userName string, newPwd string) (req *ChangePasswordRequest) {
ts, sign := GetSign()
req = &ChangePasswordRequest{
RpcRequest: &requests.RpcRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/remote_login.php")
req.FormParams = map[string]string{
"act": "getpwd",
"do": "passwd",
"username": userName,
"newpwd": newPwd,
"time": fmt.Sprintf("%v", ts),
"sign": sign,
"format": "json",
}
req.Method = requests.POST
return
}
func CreateChangePasswordResponse() (response *ChangePasswordResponse) {
response = &ChangePasswordResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}
type ChangePasswordResponse struct {
*responses.BaseResponse
}

View File

@ -1,51 +0,0 @@
package passport
import (
"fmt"
"github.com/spf13/cast"
_ "github.com/spf13/cast"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
)
type UpdateUserStateRequest struct {
*requests.RpcRequest
}
type UpdateUserStateResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
State int `json:"state"`
} `json:"data"`
}
// CreateUpdateUserStateRequest 获取用户登录过的游戏大类
func CreateUpdateUserStateRequest(userName string, uid, state int) (req *UpdateUserStateRequest) {
ts, sign := GetSign()
req = &UpdateUserStateRequest{
RpcRequest: &requests.RpcRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/remote_login.php")
req.FormParams = map[string]string{
"act": "update",
"do": "update_user_state",
"user_name": userName,
"uid": cast.ToString(uid),
"state": cast.ToString(state),
"time": fmt.Sprintf("%v", ts),
"sign": sign,
}
req.Method = requests.POST
return
}
func CreateUpdateUserStateResponse() (response *UpdateUserStateResponse) {
response = &UpdateUserStateResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -1,202 +0,0 @@
package passport
import (
"crypto/md5"
"encoding/hex"
"fmt"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
"time"
)
type GetUserListRequest struct {
*requests.RpcRequest
}
type GetUserListResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data []UserInfo `json:"data"`
}
type UserInfo struct {
Id string `json:"id"`
Uid string `json:"uid"`
BbsUid string `json:"bbs_uid"`
UserName string `json:"user_name"`
UserPwd string `json:"user_pwd"`
Email string `json:"email"`
Integral string `json:"integral"`
NickName string `json:"nick_name"`
TrueName string `json:"true_name"`
Sex string `json:"sex"`
IdType string `json:"id_type"`
IdCard string `json:"id_card"`
Birthday string `json:"birthday"`
Telephone string `json:"telephone"`
Mobile string `json:"mobile"`
Address string `json:"address"`
Zipcode int64 `json:"zipcode"`
Level string `json:"level"`
Qq string `json:"qq"`
Msn string `json:"msn"`
Question string `json:"question"`
Answer string `json:"answer"`
HeadPic string `json:"head_pic"`
Defendboss string `json:"defendboss"`
RegTime int64 `json:"reg_time"`
RegIp string `json:"reg_ip"`
LoginIp string `json:"login_ip"`
LoginTime string `json:"login_time"`
State string `json:"state"`
}
// CreateGetUserListRequest 获取玩家用户列表
func CreateGetUserListRequest(userName string) (req *GetUserListRequest) {
ts, sign := GetSign()
req = &GetUserListRequest{
RpcRequest: &requests.RpcRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/remote_login.php")
req.FormParams = map[string]string{
"act": "info",
"do": "get_user_list",
"user_names": userName,
"time": fmt.Sprintf("%v", ts),
"sign": sign,
}
req.Method = requests.POST
return
}
func CreateGetUserListResponse() (response *GetUserListResponse) {
response = &GetUserListResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}
type GetUserRoleListRequest struct {
*requests.RpcRequest
}
type GetUserRoleListResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data []UserRoleInfo `json:"data"`
}
type UserRoleInfo struct {
Uid string `json:"uid"` // uid
GameId string `json:"game_id"` // 子游戏id
RoleId string `json:"role_id"` // 角色id
RoleName string `json:"role_name"` // 角色名
RoleServer string `json:"role_server"` // 角色服务器名
AddTime string `json:"add_time"` // 创建时间戳
UpdateTime string `json:"update_time"` // 更新时间戳
}
// GetSign 封装一个方法获取当天时间戳和api签名
func GetSign() (ts int64, sign string) {
ts = time.Now().Unix()
hash := md5.New()
hash.Write([]byte(fmt.Sprintf("%v%v", ts, appKey)))
hashBytes := hash.Sum(nil)
sign = hex.EncodeToString(hashBytes)
return
}
// CreateGetUserRoleListRequest 获取玩家角色列表
func CreateGetUserRoleListRequest(uid int, gameId int, roleId int, roleServer string) (req *GetUserRoleListRequest) {
ts, sign := GetSign()
req = &GetUserRoleListRequest{
RpcRequest: &requests.RpcRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/remote_login.php")
req.FormParams = map[string]string{
"act": "info",
"do": "user_role",
"method": "get",
"uid": fmt.Sprintf("%d", uid),
"game_id": fmt.Sprintf("%d", gameId),
"role_id": fmt.Sprintf("%d", roleId),
"role_server": roleServer,
"time": fmt.Sprintf("%v", ts),
"sign": sign,
}
req.Method = requests.POST
return
}
func CreateGetUserRoleListResponse() (response *GetUserRoleListResponse) {
response = &GetUserRoleListResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}
type GetUserGameSignRequest struct {
*requests.RpcRequest
}
type GetUserGameSignResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
List []UserGameSign `json:"list"`
} `json:"data"`
}
type UserGameSign struct {
Id string `json:"id"`
AgentId string `json:"agent_id"`
SiteId string `json:"site_id"`
Uid string `json:"uid"`
UserName string `json:"user_name"`
GameId string `json:"game_id"`
GameSign string `json:"game_sign"`
Oaid string `json:"oaid"`
Imei string `json:"imei"`
Imei2 string `json:"imei2"`
Ua string `json:"ua"`
FirstLoginIp string `json:"first_login_ip"`
FirstLoginTime string `json:"first_login_time"`
LastLoginIp string `json:"last_login_ip"`
LastLoginTime string `json:"last_login_time"`
}
// CreateGetUserGameSignRequest 获取用户登录过的游戏大类
func CreateGetUserGameSignRequest(userName, gameSign, orderBy string) (req *GetUserGameSignRequest) {
ts, sign := GetSign()
req = &GetUserGameSignRequest{
RpcRequest: &requests.RpcRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/remote_login.php")
req.FormParams = map[string]string{
"act": "info",
"do": "get_user_game_sign",
"username": userName,
"game_sign": gameSign,
"order_by": orderBy,
"time": fmt.Sprintf("%v", ts),
"sign": sign,
}
req.Method = requests.POST
return
}
func CreateGetUserGameSignResponse() (response *GetUserGameSignResponse) {
response = &GetUserGameSignResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -1,97 +0,0 @@
package passport
import (
"fmt"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/utils"
"time"
)
const weeDongKey = "aVCxX2B3yswpxCMjaaSUHFXAzLYyuGhW"
func weeDongGetSign(ts int64) string {
return utils.Md5(utils.Md5(fmt.Sprintf("%d", ts)+weeDongKey) + weeDongKey)
}
type EditCardRequestParam struct {
Uid int64 `position:"Body" field:"uid"`
GameId int64 `position:"Body" field:"game_id"`
Imei string `position:"Body" field:"imei"`
IsReal int64 `position:"Body" field:"is_real"`
IsDirect int64 `position:"Body" field:"is_direct"`
DirectStatus int64 `position:"Body" field:"direct_status"`
AuthChannel string `position:"Body" field:"auth_channel"`
DirectExtData string `position:"Body" field:"direct_ext_data"`
Pi string `position:"Body" field:"pi"`
Ip string `position:"Body" field:"ip"`
Ipv6 string `position:"Body" field:"ipv6"`
UserName string `position:"Body" field:"user_name"`
RealName string `position:"Body" field:"truename"`
IdCard string `position:"Body" field:"idcard"`
Mandatory string `position:"Body" field:"mandatory"`
}
type EditCardResponse struct {
*responses.BaseResponse
}
type EditCardRequest struct {
*requests.RpcRequest
Uid int64 `position:"Body" field:"uid"`
GameId int64 `position:"Body" field:"game_id"`
Imei string `position:"Body" field:"imei"`
IsReal int64 `position:"Body" field:"is_real"`
IsDirect int64 `position:"Body" field:"is_direct"`
DirectStatus int64 `position:"Body" field:"direct_status"`
AuthChannel string `position:"Body" field:"auth_channel"`
DirectExtData string `position:"Body" field:"direct_ext_data"`
Pi string `position:"Body" field:"pi"`
Ip string `position:"Body" field:"ip"`
Ipv6 string `position:"Body" field:"ipv6"`
UserName string `position:"Body" field:"user_name"`
RealName string `position:"Body" field:"truename"`
IdCard string `position:"Body" field:"idcard"`
Mandatory string `position:"Body" field:"mandatory"`
Action string `position:"Body" field:"action"`
Flag string `position:"Body" field:"flag"`
Time string `position:"Body" field:"time"`
}
// CreateEditCardRequest 记录实名结果接口
func CreateEditCardRequest(param EditCardRequestParam) (req *EditCardRequest) {
ts := time.Now().Unix()
sign := weeDongGetSign(ts)
req = &EditCardRequest{
RpcRequest: &requests.RpcRequest{},
Action: "edit_card",
Flag: sign,
Time: fmt.Sprintf("%v", ts),
IsDirect: param.IsDirect,
Uid: param.Uid,
GameId: param.GameId,
Imei: param.Imei,
IsReal: param.IsReal,
DirectStatus: param.DirectStatus,
AuthChannel: param.AuthChannel,
DirectExtData: param.DirectExtData,
Pi: param.Pi,
Ip: param.Ip,
Ipv6: param.Ipv6,
UserName: param.UserName,
RealName: param.RealName,
IdCard: param.IdCard,
Mandatory: param.Mandatory,
}
req.InitWithApiInfo(HOST, VERSION, "/weedong.php")
req.Method = requests.POST
return
}
func CreateEditCardResponse() (response *EditCardResponse) {
response = &EditCardResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -15,7 +15,7 @@ var HOST requests.Host = requests.Host{
var a = map[string]string{
requests.RELEASE: "pay.api.gaore.com",
requests.PRE: "pay.api.gaore.com",
requests.TEST: "pay.gaore.com",
requests.TEST: "pay.api.gaore.com",
}
return a[s]
},
@ -54,11 +54,3 @@ func (c *Client) MerchantConfigDebug(req *merchantConfigDebugRequest) (response
err = c.DoAction(req, response)
return
}
// GetOrderState
// 获取订单状态
func (c *Client) GetOrderState(req *GetOrderStateRequest) (response *GetOrderStateResponse, err error) {
response = CreateGetOrderStateResponse()
err = c.DoAction(req, response)
return
}

View File

@ -1,41 +1,28 @@
package pay
import (
"fmt"
"log"
"testing"
)
func TestClient_GetUserInfo(t *testing.T) {
//c, err := NewClient()
//if err != nil {
// t.Error(err)
//}
//
//req := CreateComplaintNotifyUrlRequest()
//
//req.MchId = "3503"
//req.NotifyUrl = "https://pay.uu89.com/api/complaint/wxNotify/3503"
//req.Type = 1
//
//resp, err := c.ComplaintNotifyUrl(req)
//if err != nil {
// log.Fatalln(err)
//}
//fmt.Println(resp.GetHttpContentString())
//fmt.Println(resp.GetHttpHeaders())
}
c, err := NewClient()
if err != nil {
t.Error(err)
}
func TestGetOrderState(t *testing.T) {
getOrderStateRequest := CreateGetOrderStateRequest("202112060000193551730")
client, err := NewClient()
req := CreateComplaintNotifyUrlRequest()
req.MchId = "3503"
req.NotifyUrl = "https://pay.uu89.com/api/complaint/wxNotify/3503"
req.Type = 1
resp, err := c.ComplaintNotifyUrl(req)
if err != nil {
t.Error(err)
return
log.Fatalln(err)
}
getOrderStateResponse, err := client.GetOrderState(getOrderStateRequest)
if err != nil {
t.Error(err)
return
}
t.Log(getOrderStateResponse.GetHttpContentString())
fmt.Println(resp.GetHttpContentString())
fmt.Println(resp.GetHttpHeaders())
}

View File

@ -9,8 +9,6 @@ type ComplaintCompleteRequest struct {
*requests.RpcRequest
MchId string `position:"Body" field:"mch_id" default:"" `
ComplaintId string `position:"Body" field:"complaint_id" default:"" `
ExtData string `position:"Body" field:"ext_data" default:"" `
PayType int `position:"Body" field:"pay_type" default:"" `
}
type ComplaintCompleteResponse struct {

View File

@ -11,7 +11,6 @@ type ComplaintReplyRequest struct {
ComplaintId string `position:"Body" field:"complaint_id" default:"" `
Content string `position:"Body" field:"content" default:"" `
Images string `position:"Body" field:"images" default:"" `
PayType int `position:"Body" field:"pay_type" default:"" `
}
type ComplaintReplyResponse struct {

View File

@ -10,7 +10,6 @@ type ComplaintUploadRequest struct {
MchId string `position:"Body" field:"mch_id" default:"" `
ImageUrl string `position:"Body" field:"image_url" default:"" `
ComplaintId string `position:"Body" field:"complaint_id" default:" " `
PayType int `position:"Body" field:"pay_type" default:"" `
}
type ComplaintUploadResponse struct {

View File

@ -1,44 +0,0 @@
package pay
import (
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
)
type GetOrderStateRequest struct {
*requests.RpcRequest
OrderId string `position:"Body" field:"orderid" default:"" `
}
type GetOrderStateResponse struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
Orderid string `json:"orderid"` // 订单号
Succ string `json:"succ"` // 是否成功
Money string `json:"money"` // 支付金额
UserName string `json:"user_name"` // 用户名
BNum string `json:"b_num"`
GameId string `json:"game_id"` // 游戏id
PayDate string `json:"pay_date"` // 付费日期
SyncDate string `json:"sync_date"` // 回调时间
} `json:"data"`
}
func CreateGetOrderStateRequest(orderId string) (req *GetOrderStateRequest) {
req = &GetOrderStateRequest{
RpcRequest: &requests.RpcRequest{},
OrderId: orderId,
}
req.InitWithApiInfo(HOST, VERSION, "/api/user/getOrderState")
req.Method = requests.POST
return
}
func CreateGetOrderStateResponse() (response *GetOrderStateResponse) {
response = &GetOrderStateResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -7,8 +7,7 @@ import (
type merchantConfigDebugRequest struct {
*requests.RpcRequest
MchId string `position:"Body" field:"mch_id" default:"" `
PayType int `position:"Body" field:"pay_type" default:"" `
MchId string `position:"Body" field:"mch_id" default:"" `
}
type merchantConfigDebugResponse struct {

View File

@ -33,14 +33,3 @@ func (c *Client) OpenGame(req *OpenGameReq) (resp *OpenGameResp, err error) {
return
}
// NewPayRedisData 设置支付redis相关数据
func (c *Client) NewPayRedisData(req *NewPayRedisDataReq) (resp *NewPayRedisDataResp, err error) {
resp = CreateNewPayRedisDataResp()
err = c.DoAction(req, resp)
if err != nil {
return
}
return
}

View File

@ -19,18 +19,3 @@ func TestOpenGame(t *testing.T) {
fmt.Println(resp.Code, resp.Msg)
}
func TestNewPayRedisData(t *testing.T) {
client, err := NewClient()
if err != nil {
panic(err)
}
req := CreateNewPayRedisDataReq()
resp, err := client.NewPayRedisData(req)
if err != nil {
panic(err)
}
fmt.Println(resp.Code, resp.Msg)
}

View File

@ -2,27 +2,19 @@ package script
import (
"encoding/json"
"fmt"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
)
type OpenGameReq struct {
*requests.RpcRequest
GameID int `position:"Query" field:"game_id"`
}
type OpenGameResp struct {
*responses.BaseResponse
}
type NewPayRedisDataReq struct {
*requests.RpcRequest
}
type NewPayRedisDataResp struct {
*responses.BaseResponse
}
// GetHttpContentBytes 因为http://script.gaore.com/open_game.php?game_id=这个接口返回的不是json反序列化会报错所以返回一个固定的json
func (baseResponse *OpenGameResp) GetHttpContentBytes() []byte {
b, _ := json.Marshal(map[string]interface{}{"code": 200, "msg": "success"})
@ -33,11 +25,10 @@ func (baseResponse *OpenGameResp) GetHttpContentBytes() []byte {
func CreateOpenGameReq(gameId int) *OpenGameReq {
req := &OpenGameReq{
&requests.RpcRequest{},
gameId,
}
req.InitWithApiInfo(HOST, VERSION, "open_game.php")
req.Method = requests.GET
req.InitWithApiInfo(HOST, VERSION, "open_game.php?game_id="+fmt.Sprintf("%v", gameId))
req.Method = requests.POST
return req
}
@ -48,21 +39,3 @@ func CreateOpenGameResp() *OpenGameResp {
BaseResponse: &responses.BaseResponse{},
}
}
// CreateNewPayRedisDataReq 设置支付redis相关数据
func CreateNewPayRedisDataReq() *NewPayRedisDataReq {
req := &NewPayRedisDataReq{
&requests.RpcRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "pay/new_pay_redis_data.php")
req.Method = requests.GET
return req
}
func CreateNewPayRedisDataResp() *NewPayRedisDataResp {
return &NewPayRedisDataResp{
BaseResponse: &responses.BaseResponse{},
}
}

View File

@ -1,115 +0,0 @@
package sms
import (
"crypto/md5"
"encoding/hex"
"errors"
"fmt"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"time"
)
const (
VERSION = "2024-05-30"
)
var HOST = requests.Host{
Default: "sms.gaore.com",
}
type Client struct {
sdk.Client
}
func NewClient() (client *Client, err error) {
client = new(Client)
err = client.Init()
return
}
func (c *Client) SendEmail(req *SendEmailRequest) (resp *SendEmailResponse, err error) {
if len(req.Addresses) == 0 {
return nil, errors.New("addresses is empty")
}
if req.FromName == "" {
return nil, errors.New("from is empty")
}
if req.Subject == "" {
return nil, errors.New("subject is empty")
}
if req.Body == "" {
return nil, errors.New("content is empty")
}
ts, token := getToken("04573fc4c8e01999a0909ab9c00bca5a")
req.JsonParams["sign"] = token
req.JsonParams["time"] = ts
resp = CreateSendEmailResponse()
err = c.DoAction(req, resp)
return
}
func (c *Client) SendFeiShuWebHook(req *SendFeiShuWebHookRequest) (resp *SendFeiShuWebHookResponse, err error) {
if req.Content == "" {
err = errors.New("content is empty")
return
}
if req.Do == "" {
err = errors.New("webhook is empty")
return
}
if req.Token == "" {
err = errors.New("token is empty")
return
}
resp = CreateSendFeiShuWebHookResponse()
err = c.DoAction(req, resp)
return
}
func (c *Client) SendSms(req *SendSmsRequest) (resp *SendSmsResponse, err error) {
if req.Mobile == "" {
err = errors.New("mobile is empty")
return
}
if req.Type == "" {
err = errors.New("type is empty")
return
}
resp = CreateSendSmsResponse()
err = c.DoAction(req, resp)
return
}
func (c *Client) SendSmsV2(req *SendSmsRequestV2) (resp *SendSmsResponseV2, err error) {
if req.Phone == "" {
err = errors.New("phone is empty")
return
}
if req.Type == "" {
err = errors.New("type is empty")
return
}
resp = CreateSendSmsResponseV2()
err = c.DoAction(req, resp)
return
}
func getToken(key string) (ts int64, token string) {
ts = time.Now().Unix()
hash := md5.New()
hash.Write([]byte(fmt.Sprintf("%v%v", ts, key)))
hashBytes := hash.Sum(nil)
token = hex.EncodeToString(hashBytes)
return
}

View File

@ -1,170 +0,0 @@
package sms
import (
"encoding/json"
"fmt"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"testing"
)
var (
client *Client
)
func TestMain(t *testing.M) {
var err error
client, err = NewClient()
if err != nil {
panic(err)
}
t.Run()
}
func TestClient_SendEmail(t *testing.T) {
req := CreateSendEmailRequest(SendEmailParam{
Addresses: []string{"xuyang@89you.com"},
Subject: "测试邮件",
Body: "xxx已修改密码新密码是xxx",
FromName: "高热监控",
})
email, err := client.SendEmail(req)
if err != nil {
panic(err)
}
fmt.Println(email)
}
func TestClient_SendFeiShuWebHook(t *testing.T) {
//req := CreateSendFeiShuWebHookRequest(SendFeiShuWebHookParam{
// Do: FeiShuWebHookDoTypeSendRichText,
// Token: "b762f80c-fe4f-4182-b48e-5c78041592bc",
// Content: "[[{\"tag\":\"text\",\"text\":\"富文本信息: \"},{\"tag\":\"a\",\"text\":\"请查看\",\"href\":\"http://www.example.com/\"},{\"tag\":\"at\",\"user_id\":\"ou_18eac8********17ad4f02e8bbbb\"}]]",
// Title: "卡片主标题",
// TitleColor: "purple",
//})
//
//resp, err := client.SendFeiShuWebHook(req)
//if err != nil {
// panic(err)
//}
//fmt.Println(resp.Msg)
//req2 := CreateSendFeiShuWebHookRequest(SendFeiShuWebHookParam{
// Do: FeiShuWebHookDoTypeSendSimpleText,
// Token: "b762f80c-fe4f-4182-b48e-5c78041592bc",
// Content: " - 苹果IDXXXX\n - 游戏IDXXXX\n - bundleIDXXXX\n - 应用名XXX\n - 下架时间2025-04-18 123652\n - IPXX城市A省份、XX城市B省份说明XX为具体的IP括号内为IP对应的城市",
//})
//
//resp2, err := client.SendFeiShuWebHook(req2)
//if err != nil {
// panic(err)
//}
//fmt.Println(resp2)
//[
// [
// {
// "tag": "text",
// "text": "苹果IDXXXX"
// }
// ],
// [
// {
// "tag": "text",
// "text": "游戏IDXXXX"
// }
// ]
//]
req3 := CreateSendFeiShuWebHookRequest(SendFeiShuWebHookParam{
TitleColor: "purple",
Title: "监控报警",
Do: FeiShuWebHookDoTypeSendCardText,
Token: "b762f80c-fe4f-4182-b48e-5c78041592bc",
Content: "[{\"tag\":\"div\",\"text\":{\"tag\":\"plain_text\",\"content\":\"苹果IDXXXX\"}},{\"tag\":\"div\",\"text\":{\"tag\":\"plain_text\",\"content\":\"游戏IDXXXX\"}}]",
})
resp3, err := client.SendFeiShuWebHook(req3)
if err != nil {
panic(err)
}
fmt.Println(resp3.Msg)
fmt.Println(resp3)
}
func TestClient_SendSmsCode(t *testing.T) {
req := CreateSendSmsRequest(SendSmsParam{
Mobile: "18320021439",
Type: SmsTypeBindPhone,
Replaces: []Item{{
Key: ReplaceKeyCode,
Value: "6379",
}, {
Key: ReplaceKeySecond,
Value: "120",
}},
})
req.Domain = requests.Host{
Default: "127.0.0.1:8804",
}
sms, err := client.SendSms(req)
if err != nil {
panic(err)
}
fmt.Println(sms)
}
func TestClient_SendSmsUrl(t *testing.T) {
req := CreateSendSmsRequest(SendSmsParam{
Mobile: "18320021439",
Type: TemplateTypeOrderComplete,
Replaces: []Item{{
Key: ReplaceKeyUrl,
Value: "http://www.baidu.com",
}},
})
req.Domain = requests.Host{
Default: "127.0.0.1:8804",
}
sms, err := client.SendSms(req)
if err != nil {
panic(err)
}
fmt.Println(sms)
}
func TestClient_SendSmsCodeV2(t *testing.T) {
req := CreateSendSmsRequestV2(SendSmsParamV2{
Phone: "18320021439",
Type: SmsTypeRegister,
Replaces: []Item{{
Key: ReplaceKeyCode,
Value: "6379",
}, {
Key: ReplaceKeySecond,
Value: "120",
}},
Company: "",
Ip: "192.168.1.103",
})
sms, err := client.SendSmsV2(req)
if err != nil {
panic(err)
}
marshal, err := json.Marshal(sms)
if err != nil {
panic(err)
}
fmt.Println(string(marshal))
}

View File

@ -1,45 +0,0 @@
package sms
import (
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
)
type SendEmailRequest struct {
*requests.JsonRequest
Addresses []string `position:"Json" field:"addresses"`
Subject string `position:"Json" field:"subject"`
Body string `position:"Json" field:"body"`
FromName string `position:"Json" field:"from_name"`
}
type SendEmailResponse struct {
*responses.BaseResponse
}
type SendEmailParam struct {
Addresses []string
Subject string
Body string
FromName string
}
func CreateSendEmailRequest(param SendEmailParam) (req *SendEmailRequest) {
req = &SendEmailRequest{
JsonRequest: &requests.JsonRequest{},
Addresses: param.Addresses,
Subject: param.Subject,
Body: param.Body,
FromName: param.FromName,
}
req.InitWithApiInfo(HOST, VERSION, "/v1/email/send")
req.Method = requests.POST
return
}
func CreateSendEmailResponse() (resp *SendEmailResponse) {
resp = &SendEmailResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -1,57 +0,0 @@
package sms
import (
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
)
type SendFeiShuWebHookRequest struct {
*requests.JsonRequest
Do string `position:"Json" field:"do"`
Token string `position:"Json" field:"token"`
Content string `position:"Json" field:"content"`
Title string `position:"Json" field:"title"`
TitleColor string `position:"Json" field:"title_color"`
}
type SendFeiShuWebHookResponse struct {
*responses.BaseResponse
FeishuData string `json:"feishu_data"`
}
type FeiShuWebHookDoType = string
const (
FeiShuWebHookDoTypeSendSimpleText FeiShuWebHookDoType = "sendSimpleText"
FeiShuWebHookDoTypeSendRichText FeiShuWebHookDoType = "sendRichText"
FeiShuWebHookDoTypeSendCardText FeiShuWebHookDoType = "sendCardText"
)
type SendFeiShuWebHookParam struct {
Do FeiShuWebHookDoType
Token string
Content string
Title string
TitleColor string
}
func CreateSendFeiShuWebHookRequest(param SendFeiShuWebHookParam) (req *SendFeiShuWebHookRequest) {
req = &SendFeiShuWebHookRequest{
JsonRequest: &requests.JsonRequest{},
Do: param.Do,
Token: param.Token,
Content: param.Content,
Title: param.Title,
TitleColor: param.TitleColor,
}
req.InitWithApiInfo(HOST, VERSION, "/v1/feishu/webhook_send")
req.Method = requests.POST
return
}
func CreateSendFeiShuWebHookResponse() (resp *SendFeiShuWebHookResponse) {
resp = &SendFeiShuWebHookResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -1,111 +0,0 @@
package sms
import (
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
)
type ReplaceKey = string
const (
ReplaceKeyCode ReplaceKey = "${code}" // 验证码
ReplaceKeySecond ReplaceKey = "${second}" // 秒数
ReplaceKeyUrl ReplaceKey = "${url}" // 链接
ReplaceKeyUserName ReplaceKey = "${userName}" // 用户名
ReplaceKeyDateTime ReplaceKey = "${dateTime}" // 年月日时分秒
)
type Item struct {
Key ReplaceKey // 要替换的key
Value string // 要替换的值
}
type SendSmsRequest struct {
*requests.JsonRequest
Mobile string `position:"Json" field:"mobile"`
Type string `position:"Json" field:"type"`
Replaces []Item `position:"Json" field:"replaces"`
}
type SendSmsResponse struct {
*responses.BaseResponse
}
type SendSmsRequestV2 struct {
*requests.JsonRequest
Phone string `position:"Json" field:"phone"`
Type string `position:"Json" field:"type"`
Replaces []Item `position:"Json" field:"replaces"`
Company string `position:"Json" field:"company"`
Ip string `position:"Json" field:"ip"`
}
type SendSmsResponseV2 struct {
*responses.BaseResponse
TraceID string `json:"trace_id"`
}
type SmsType = string
const (
SmsTypeRegister SmsType = "reg" // 注册
SmsTypeBindPhone SmsType = "bind_phone" // 绑定手机号
TemplateTypeOrderComplete SmsType = "kf_order_complete" // 客服工单完成
TemplateTypeKFOrderAdditional SmsType = "kf_order_additional" // 客服工单完成
TemplateTypeCancelTip SmsType = "cancel_tip" // 提交账号注销申请
TemplateTypeReverseCancel SmsType = "reverse_cancel" // 终止账号注销申请
)
type SendSmsParam struct {
Mobile string // 手机号
Type SmsType // 验证码类型
Replaces []Item
}
type SendSmsParamV2 struct {
Phone string // 手机号
Type SmsType // 验证码类型
Replaces []Item
Company string // 子游戏公司主体
Ip string // ip
}
func CreateSendSmsRequest(param SendSmsParam) (req *SendSmsRequest) {
req = &SendSmsRequest{
JsonRequest: &requests.JsonRequest{},
Mobile: param.Mobile,
Type: param.Type,
Replaces: param.Replaces,
}
req.InitWithApiInfo(HOST, VERSION, "/v1/sms/send")
req.Method = requests.POST
return
}
func CreateSendSmsResponse() (resp *SendSmsResponse) {
resp = &SendSmsResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}
func CreateSendSmsRequestV2(param SendSmsParamV2) (req *SendSmsRequestV2) {
req = &SendSmsRequestV2{
JsonRequest: &requests.JsonRequest{},
Phone: param.Phone,
Type: param.Type,
Replaces: param.Replaces,
Company: param.Company,
Ip: param.Ip,
}
req.InitWithApiInfo(HOST, VERSION, "/v2/sms/send")
req.Method = requests.POST
return
}
func CreateSendSmsResponseV2() (resp *SendSmsResponseV2) {
resp = &SendSmsResponseV2{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -1,77 +0,0 @@
package stat
import (
"crypto/md5"
"encoding/hex"
"fmt"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
"time"
)
type GetAgentListReq struct {
*requests.RpcRequest
}
/**
返回json格式如下
{
code": 0,
"msg": "success",
"data": {
"list": []
}
}
*/
type GetAgentListResp struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data AgentList `json:"data"`
}
type AgentList struct {
List []Agent `json:"list"`
}
type Agent struct {
AgentId string `json:"agent_id"`
AgentName string `json:"agent_name"`
Media string `json:"media"`
Channel string `json:"channel"`
MediaName string `json:"media_name"`
ChannelName string `json:"channel_name"`
}
//const key = "gr_new_game"
// CreateGetAgentListReq 获取推广渠道列表请求
func CreateGetAgentListReq(data map[string]string) *GetAgentListReq {
req := &GetAgentListReq{
&requests.RpcRequest{},
}
ts := time.Now().Unix()
hash := md5.New()
hash.Write([]byte(fmt.Sprintf("%v%v", ts, key)))
hashBytes := hash.Sum(nil)
token := hex.EncodeToString(hashBytes)
req.InitWithApiInfo(HOST, VERSION, "/agent/getAgentList")
req.Method = requests.POST
req.FormParams = data
if req.FormParams == nil {
req.FormParams = make(map[string]string)
}
req.FormParams["sign"] = token
req.FormParams["time"] = fmt.Sprintf("%v", ts)
return req
}
// CreateGetAgentListResp 获取推广渠道列表响应
func CreateGetAgentListResp() *GetAgentListResp {
return &GetAgentListResp{
BaseResponse: &responses.BaseResponse{},
}
}

View File

@ -3,7 +3,6 @@ package stat
import (
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"time"
)
const (
@ -40,37 +39,3 @@ func (c *Client) SetUserNewGameAuth(req *SetUserNewGameAuthReq) (resp *SetUserNe
err = c.DoAction(req, resp)
return
}
// GetAgentList 获取推广渠道列表
func (c *Client) GetAgentList(req *GetAgentListReq) (resp *GetAgentListResp, err error) {
resp = CreateGetAgentListResp()
err = c.DoAction(req, resp)
if err != nil {
return
}
return
}
// GetUserRoleRegPage 获取用户角色注册分页列表
func (c *Client) GetUserRoleRegPage(req *UserRoleRegReq) (resp *UserRoleRegResp, err error) {
resp = CreateUserRoleRegPageResp()
// 设置超时时间
req.SetConnectTimeout(10 * time.Second)
// 设置读取超时时间
req.SetReadTimeout(20 * time.Second)
err = c.DoAction(req, resp)
if err != nil {
return
}
return
}
// GetUserTotalPay 获取用户累计付费
func (c *Client) GetUserTotalPay(req *GetUserTotalPayReq) (resp *GetUserTotalPayResp, err error) {
resp = CreateGetUserTotalPayResp()
err = c.DoAction(req, resp)
if err != nil {
return
}
return
}

View File

@ -52,68 +52,3 @@ func TestClient_SetUserNewGameAuth(t *testing.T) {
fmt.Println(resp.Code, resp.Msg, resp.Data.Result)
}
// TestClient_GetAgentList 查询代理列表单元测试
func TestClient_GetAgentList(t *testing.T) {
client, err := NewClient()
if err != nil {
panic(err)
}
req := CreateGetAgentListReq(map[string]string{
"agent_id": "4051,68017",
//"agent_id": "99",
})
resp, err := client.GetAgentList(req)
if err != nil {
panic(err)
}
fmt.Println(resp.Code, resp.Msg, resp.Data)
// 断言 resp.Code = 1且 resp.Data 不空为正常
if resp.Code != 1 || len(resp.Data.List) == 0 {
t.Errorf("GetAgentList test failed")
} else {
t.Log("GetAgentList test passed")
}
}
// TestClient_GetUserRoleRegPage 查询用户角色注册分页
func TestClient_GetUserRoleRegPage(t *testing.T) {
client, err := NewClient()
if err != nil {
panic(err)
}
req := CreateUserRoleRegPageReq(UserRoleRegParam{
Page: 1,
PageSize: 10,
RoleId: "",
RoleName: "温文波箐魔灵",
})
resp, err := client.GetUserRoleRegPage(req)
if err != nil {
panic(err)
}
fmt.Println(resp.Code, resp.Msg, resp.Data)
}
// 获取用户累计付费
func TestGetUserTotalPay(t *testing.T) {
client, err := NewClient()
if err != nil {
panic(err)
}
req := CreateGetUserTotalPayReq(GetUserTotalPayParam{
Where: "user_name = 'yoyo685757'",
Fields: []string{"user_name", "sum(total_pay_money) as total_pay_money", "last_pay_time"},
GroupBy: []string{"user_name"},
})
resp, err := client.GetUserTotalPay(req)
if err != nil {
panic(err)
}
fmt.Println(resp.Code, resp.Msg, resp.Data)
}

View File

@ -1,63 +0,0 @@
package stat
import (
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
"strings"
)
type GetUserTotalPayReq struct {
*requests.RpcRequest
}
type GetUserTotalPayParam struct {
Where string `json:"where"`
Fields []string `json:"fields"`
GroupBy []string `json:"group_by"`
}
type GetUserTotalPayResp struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data TotalPayList `json:"data"`
}
type TotalPayList struct {
List []TotalPay `json:"list"`
}
type TotalPay struct {
UserName string `json:"user_name"`
RegDate string `json:"reg_date"`
AgentId int64 `json:"agent_id"`
SiteId int64 `json:"site_id"`
GameId int64 `json:"game_id"`
FirstPayTime string `json:"first_pay_time"`
FirstPayMoney float64 `json:"first_pay_money"`
TotalPayMoney float64 `json:"total_pay_money"`
LastPayTime string `json:"last_pay_time"`
PayTimes int64 `json:"pay_times"`
IsFirst int64 `json:"is_first"`
}
// CreateGetUserTotalPayReq 获取用户累充
func CreateGetUserTotalPayReq(data GetUserTotalPayParam) *GetUserTotalPayReq {
req := &GetUserTotalPayReq{
&requests.RpcRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/pay/getUserTotalPay")
req.Method = requests.POST
req.FormParams = make(map[string]string)
req.FormParams["where"] = data.Where
req.FormParams["fields"] = strings.Join(data.Fields, ",")
req.FormParams["group_by"] = strings.Join(data.GroupBy, ",")
return req
}
// CreateGetUserTotalPayResp 获取用户累充
func CreateGetUserTotalPayResp() *GetUserTotalPayResp {
return &GetUserTotalPayResp{
BaseResponse: &responses.BaseResponse{},
}
}

View File

@ -57,59 +57,3 @@ func CreateSetUserNewGameAuthResp() *SetUserNewGameAuthResp {
BaseResponse: &responses.BaseResponse{},
}
}
// ------------------------------------
// UserRoleReg 玩家汇总角色创建记录
type UserRoleReg struct {
UserName string `json:"user_name"`
Uid string `json:"uid"`
RoleId string `json:"role_id"`
RoleName string `json:"role_name"`
GameSign string `json:"game_sign"`
Id string `json:"id"`
CreatedAt string `json:"created_at"`
}
type UserRoleRegPage struct {
Page int `json:"page"`
TotalCount int `json:"total_count"`
PageSize int `json:"page_size"`
Data []UserRoleReg `json:"data"`
}
type UserRoleRegParam struct {
Page int `json:"page"`
PageSize int `json:"page_size"`
RoleId string `json:"role_id"`
RoleName string `json:"role_name"`
}
type UserRoleRegReq struct {
*requests.RpcRequest
}
type UserRoleRegResp struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data UserRoleRegPage `json:"data"`
}
func CreateUserRoleRegPageReq(param UserRoleRegParam) *UserRoleRegReq {
req := &UserRoleRegReq{
&requests.RpcRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/user/getRoleRegPage")
req.Method = requests.POST
req.FormParams = map[string]string{
"page": fmt.Sprintf("%v", param.Page),
"page_size": fmt.Sprintf("%v", param.PageSize),
"role_id": param.RoleId,
"role_name": param.RoleName,
}
return req
}
func CreateUserRoleRegPageResp() *UserRoleRegResp {
return &UserRoleRegResp{
BaseResponse: &responses.BaseResponse{},
}
}

View File

@ -1,55 +0,0 @@
package userlive
import (
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
)
const (
VERSION = "2020-11-16"
)
var HOST = requests.Host{
Default: "userlive",
}
type Client struct {
sdk.Client
}
func NewClient() (client *Client, err error) {
client = new(Client)
err = client.Init()
return
}
// CreateBanReq 封禁
func (c *Client) CreateBanReq(req *BanReq) (resp *BanResp, err error) {
resp = CreateBanResp()
err = c.DoAction(req, resp)
if err != nil {
return
}
return
}
// CreateAddBanRuleCacheReq 添加封禁规则缓存
func (c *Client) CreateAddBanRuleCacheReq(req *AddBanRuleCacheReq) (resp *AddBanRuleCacheResp, err error) {
resp = CreateAddBanRuleCacheResp()
err = c.DoAction(req, resp)
if err != nil {
return
}
return
}
// CreateRemoveBanRuleCacheReq 删除封禁规则缓存
func (c *Client) CreateRemoveBanRuleCacheReq(req *RemoveBanRuleCacheReq) (resp *RemoveBanRuleCacheResp, err error) {
resp = CreateRemoveBanRuleCacheResp()
err = c.DoAction(req, resp)
if err != nil {
return
}
return
}

View File

@ -1,104 +0,0 @@
package userlive
import (
"fmt"
"testing"
"time"
)
// 踢人
func TestBan(t *testing.T) {
client, err := NewClient()
if err != nil {
panic(err)
}
req := CreateBanReq(BanReqParam{
ActionTime: time.Now().Unix(),
TriggerType: triggerTypeLogin,
Ip: "127.0.0.1",
GameId: 8654,
UserName: "aq36604627",
Uid: 632308087,
ServerId: 123,
RoleId: "123",
BundleId: "asdfas",
GameName: "fasdf",
GameVersion: "fasdf",
SdkVersion: "fasdf",
Os: "fasd",
OsVersion: "faf",
InApp: "fasdf",
Ua: "fasdfas",
NetworkType: "fasdfa",
IsVirtual: "-1",
Cpu: "cpu",
DeviceModel: "dfasdf",
Baseband: "fasdfa",
Resolution: "fasdfa",
Battery: "fasdf",
LongId: "fasdf",
OriginImei: "fasdf",
Imei: "fasdf",
OriginOaid: "fasdf",
Oaid: "fasdf",
AndroidId: "fasdf",
Idfa: "fsdf",
Idfv: "fasdf",
DeviceId: "fasdf",
})
resp, err := client.CreateBanReq(req)
if err != nil {
panic(err)
}
fmt.Println(resp.Code, resp.Msg, resp.Data)
}
// 添加封禁规则
func TestAddBanRuleCache(t *testing.T) {
client, err := NewClient()
if err != nil {
panic(err)
}
req := CreateAddBanRuleCacheReq(RuleInfo{
Id: 21,
Phone: "13247173568",
UserName: "gr24616919",
IdCard: "",
DeviceId: "device_id1",
LongId: "long_id1",
IsVirtual: 0,
EndTime: "2029-01-01",
})
resp, err := client.CreateAddBanRuleCacheReq(req)
if err != nil {
panic(err)
}
fmt.Println(resp.Code, resp.Msg, resp.Data)
}
// 删除封禁规则
func TestRemoveBanRuleCache(t *testing.T) {
client, err := NewClient()
if err != nil {
panic(err)
}
infos := []RuleInfo{{
Id: 21,
Phone: "13247173568",
UserName: "gr24616919",
IdCard: "",
DeviceId: "device_id1",
LongId: "long_id1",
IsVirtual: 0,
EndTime: "2029-01-01",
}}
req := CreateRemoveBanRuleCacheReq(RemoveBanRuleCacheReqParam{Rules: infos})
resp, err := client.CreateRemoveBanRuleCacheReq(req)
if err != nil {
panic(err)
}
fmt.Println(resp.Code, resp.Msg, resp.Data)
}

View File

@ -1,159 +0,0 @@
package userlive
import (
"encoding/json"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/requests"
"golib.gaore.com/GaoreGo/gaore-common-sdk-go/sdk/responses"
)
const (
triggerTypeHeartbeat = "heartbeat" // 心跳上报触发
triggerTypeLogin = "login" // 用户登录、注册
)
// BanReq
// 上报用户设备信息,判断是否要踢用户下线
type BanReq struct {
*requests.JsonRequest
}
type BanResp struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
Ban bool `json:"ban"` // 是否要禁止
BanRuleId int64 `json:"ban_rule_id"` // 命中的封禁规则id
} `json:"data"`
}
type BanReqParam struct {
ActionTime int64 `json:"action_time" form:"action_time"` // 上报时间
TriggerType string `json:"trigger_type" form:"trigger_type"` // 触发类型
Ip string `json:"ip" form:"ip"` // ip
GameId int64 `json:"game_id" form:"game_id"` // 游戏id
UserName string `json:"user_name" form:"user_name"` // 用户名
Uid int64 `json:"uid" form:"uid"` // 用户id
ServerId string `json:"server_id" form:"server_id"` // 区服id
RoleId string `json:"role_id" form:"role_id"` // 角色id
BundleId string `json:"bundle_id" form:"bundle_id"` // ios 包名
GameName string `json:"game_name" from:"game_name"` // 应用名
GameVersion string `json:"game_version" from:"game_version"` // 游戏版本
SdkVersion string `json:"sdk_version" from:"sdk_version"` // sdk版本
Os string `json:"os" from:"os"` // 系统
OsVersion string `json:"os_version" from:"os_version"` // 系统版本
InApp string `json:"in_app" from:"in_app"` // 壳包系统,壳包传 如ios、android
Ua string `json:"ua" from:"ua"` // ua
NetworkType string `json:"network_type" from:"network_type"` // 网络类型
IsVirtual string `json:"is_virtual" from:"is_virtual"` // 是否是模拟器字符串01空字符串表示未知
Cpu string `json:"cpu" from:"cpu"` // cpu型号
DeviceModel string `json:"device_model" from:"device_model"` // 设备型号
Baseband string `json:"baseband" from:"baseband"` // 基带信息
Resolution string `json:"resolution" from:"resolution"` // 分辨率
Battery string `json:"battery" from:"battery"` // 电量
LongId string `json:"long_id" form:"long_id"` // 逻辑设备号
OriginImei string `json:"origin_imei" form:"origin_imei"` // imei原值
Imei string `json:"imei" form:"imei"` // 老sdk采集的imei
OriginOaid string `json:"origin_oaid" form:"origin_oaid"` // oaid原值
Oaid string `json:"oaid" form:"oaid"` // 老sdk采集的oaid
AndroidId string `json:"android_id" form:"android_id"` // 安卓id
Idfa string `json:"idfa" form:"idfa"` // idfa
Idfv string `json:"idfv" form:"idfv"` // idfv
DeviceId string `json:"device_id" form:"device_id"` // device_id
}
func CreateBanReq(data BanReqParam) *BanReq {
req := &BanReq{
&requests.JsonRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/api/user_ban/ban")
req.Method = requests.POST
marshal, _ := json.Marshal(data)
_ = json.Unmarshal(marshal, &req.JsonParams)
return req
}
// CreateBanResp 创建同步开服数据响应
func CreateBanResp() *BanResp {
return &BanResp{
BaseResponse: &responses.BaseResponse{},
}
}
// AddBanRuleCacheReq
// 添加封禁规则缓存
type AddBanRuleCacheReq struct {
*requests.JsonRequest
}
type AddBanRuleCacheResp struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data struct{} `json:"data"`
}
type RuleInfo struct {
Id int64 `json:"id"`
Phone string `json:"phone"`
UserName string `json:"user_name"`
IdCard string `json:"id_card"`
DeviceId string `json:"device_id"`
LongId string `json:"long_id"`
IsVirtual int64 `json:"is_virtual"`
EndTime string `json:"end_time"`
}
func CreateAddBanRuleCacheReq(data RuleInfo) *AddBanRuleCacheReq {
req := &AddBanRuleCacheReq{
&requests.JsonRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/api/user_ban/add_cache")
req.Method = requests.POST
marshal, _ := json.Marshal(data)
_ = json.Unmarshal(marshal, &req.JsonParams)
return req
}
func CreateAddBanRuleCacheResp() *AddBanRuleCacheResp {
return &AddBanRuleCacheResp{
BaseResponse: &responses.BaseResponse{},
}
}
// RemoveBanRuleCacheReq
// 删除封禁规则缓存
type RemoveBanRuleCacheReq struct {
*requests.JsonRequest
}
type RemoveBanRuleCacheReqParam struct {
Rules []RuleInfo `json:"rules"`
}
type RemoveBanRuleCacheResp struct {
*responses.BaseResponse
Code int `json:"code"`
Msg string `json:"msg"`
Data struct{} `json:"data"`
}
func CreateRemoveBanRuleCacheReq(param RemoveBanRuleCacheReqParam) *RemoveBanRuleCacheReq {
req := &RemoveBanRuleCacheReq{
&requests.JsonRequest{},
}
req.InitWithApiInfo(HOST, VERSION, "/api/user_ban/remove_cache")
req.Method = requests.POST
marshal, _ := json.Marshal(param)
_ = json.Unmarshal(marshal, &req.JsonParams)
return req
}
func CreateRemoveBanRuleCacheResp() *RemoveBanRuleCacheResp {
return &RemoveBanRuleCacheResp{
BaseResponse: &responses.BaseResponse{},
}
}

View File

@ -1,3 +0,0 @@
ignore:
- "output_tests/.*"

View File

@ -1,4 +0,0 @@
/vendor
/bug_test.go
/coverage.txt
/.idea

View File

@ -1,14 +0,0 @@
language: go
go:
- 1.8.x
- 1.x
before_install:
- go get -t -v ./...
script:
- ./test.sh
after_success:
- bash <(curl -s https://codecov.io/bash)

View File

@ -1,21 +0,0 @@
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
[[projects]]
name = "github.com/modern-go/concurrent"
packages = ["."]
revision = "e0a39a4cb4216ea8db28e22a69f4ec25610d513a"
version = "1.0.0"
[[projects]]
name = "github.com/modern-go/reflect2"
packages = ["."]
revision = "4b7aa43c6742a2c18fdef89dd197aaae7dac7ccd"
version = "1.0.1"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "ea54a775e5a354cb015502d2e7aa4b74230fc77e894f34a838b268c25ec8eeb8"
solver-name = "gps-cdcl"
solver-version = 1

View File

@ -1,26 +0,0 @@
# Gopkg.toml example
#
# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
# for detailed Gopkg.toml documentation.
#
# required = ["github.com/user/thing/cmd/thing"]
# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
#
# [[constraint]]
# name = "github.com/user/project"
# version = "1.0.0"
#
# [[constraint]]
# name = "github.com/user/project2"
# branch = "dev"
# source = "github.com/myfork/project2"
#
# [[override]]
# name = "github.com/x/y"
# version = "2.4.0"
ignored = ["github.com/davecgh/go-spew*","github.com/google/gofuzz*","github.com/stretchr/testify*"]
[[constraint]]
name = "github.com/modern-go/reflect2"
version = "1.0.1"

View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2016 json-iterator
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,85 +0,0 @@
[![Sourcegraph](https://sourcegraph.com/github.com/json-iterator/go/-/badge.svg)](https://sourcegraph.com/github.com/json-iterator/go?badge)
[![GoDoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](https://pkg.go.dev/github.com/json-iterator/go)
[![Build Status](https://travis-ci.org/json-iterator/go.svg?branch=master)](https://travis-ci.org/json-iterator/go)
[![codecov](https://codecov.io/gh/json-iterator/go/branch/master/graph/badge.svg)](https://codecov.io/gh/json-iterator/go)
[![rcard](https://goreportcard.com/badge/github.com/json-iterator/go)](https://goreportcard.com/report/github.com/json-iterator/go)
[![License](http://img.shields.io/badge/license-mit-blue.svg?style=flat-square)](https://raw.githubusercontent.com/json-iterator/go/master/LICENSE)
[![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/json-iterator/Lobby)
A high-performance 100% compatible drop-in replacement of "encoding/json"
# Benchmark
![benchmark](http://jsoniter.com/benchmarks/go-benchmark.png)
Source code: https://github.com/json-iterator/go-benchmark/blob/master/src/github.com/json-iterator/go-benchmark/benchmark_medium_payload_test.go
Raw Result (easyjson requires static code generation)
| | ns/op | allocation bytes | allocation times |
| --------------- | ----------- | ---------------- | ---------------- |
| std decode | 35510 ns/op | 1960 B/op | 99 allocs/op |
| easyjson decode | 8499 ns/op | 160 B/op | 4 allocs/op |
| jsoniter decode | 5623 ns/op | 160 B/op | 3 allocs/op |
| std encode | 2213 ns/op | 712 B/op | 5 allocs/op |
| easyjson encode | 883 ns/op | 576 B/op | 3 allocs/op |
| jsoniter encode | 837 ns/op | 384 B/op | 4 allocs/op |
Always benchmark with your own workload.
The result depends heavily on the data input.
# Usage
100% compatibility with standard lib
Replace
```go
import "encoding/json"
json.Marshal(&data)
```
with
```go
import jsoniter "github.com/json-iterator/go"
var json = jsoniter.ConfigCompatibleWithStandardLibrary
json.Marshal(&data)
```
Replace
```go
import "encoding/json"
json.Unmarshal(input, &data)
```
with
```go
import jsoniter "github.com/json-iterator/go"
var json = jsoniter.ConfigCompatibleWithStandardLibrary
json.Unmarshal(input, &data)
```
[More documentation](http://jsoniter.com/migrate-from-go-std.html)
# How to get
```
go get github.com/json-iterator/go
```
# Contribution Welcomed !
Contributors
- [thockin](https://github.com/thockin)
- [mattn](https://github.com/mattn)
- [cch123](https://github.com/cch123)
- [Oleg Shaldybin](https://github.com/olegshaldybin)
- [Jason Toffaletti](https://github.com/toffaletti)
Report issue or pull request, or email taowen@gmail.com, or [![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/json-iterator/Lobby)

View File

@ -1,150 +0,0 @@
package jsoniter
import (
"bytes"
"io"
)
// RawMessage to make replace json with jsoniter
type RawMessage []byte
// Unmarshal adapts to json/encoding Unmarshal API
//
// Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v.
// Refer to https://godoc.org/encoding/json#Unmarshal for more information
func Unmarshal(data []byte, v interface{}) error {
return ConfigDefault.Unmarshal(data, v)
}
// UnmarshalFromString is a convenient method to read from string instead of []byte
func UnmarshalFromString(str string, v interface{}) error {
return ConfigDefault.UnmarshalFromString(str, v)
}
// Get quick method to get value from deeply nested JSON structure
func Get(data []byte, path ...interface{}) Any {
return ConfigDefault.Get(data, path...)
}
// Marshal adapts to json/encoding Marshal API
//
// Marshal returns the JSON encoding of v, adapts to json/encoding Marshal API
// Refer to https://godoc.org/encoding/json#Marshal for more information
func Marshal(v interface{}) ([]byte, error) {
return ConfigDefault.Marshal(v)
}
// MarshalIndent same as json.MarshalIndent. Prefix is not supported.
func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
return ConfigDefault.MarshalIndent(v, prefix, indent)
}
// MarshalToString convenient method to write as string instead of []byte
func MarshalToString(v interface{}) (string, error) {
return ConfigDefault.MarshalToString(v)
}
// NewDecoder adapts to json/stream NewDecoder API.
//
// NewDecoder returns a new decoder that reads from r.
//
// Instead of a json/encoding Decoder, an Decoder is returned
// Refer to https://godoc.org/encoding/json#NewDecoder for more information
func NewDecoder(reader io.Reader) *Decoder {
return ConfigDefault.NewDecoder(reader)
}
// Decoder reads and decodes JSON values from an input stream.
// Decoder provides identical APIs with json/stream Decoder (Token() and UseNumber() are in progress)
type Decoder struct {
iter *Iterator
}
// Decode decode JSON into interface{}
func (adapter *Decoder) Decode(obj interface{}) error {
if adapter.iter.head == adapter.iter.tail && adapter.iter.reader != nil {
if !adapter.iter.loadMore() {
return io.EOF
}
}
adapter.iter.ReadVal(obj)
err := adapter.iter.Error
if err == io.EOF {
return nil
}
return adapter.iter.Error
}
// More is there more?
func (adapter *Decoder) More() bool {
iter := adapter.iter
if iter.Error != nil {
return false
}
c := iter.nextToken()
if c == 0 {
return false
}
iter.unreadByte()
return c != ']' && c != '}'
}
// Buffered remaining buffer
func (adapter *Decoder) Buffered() io.Reader {
remaining := adapter.iter.buf[adapter.iter.head:adapter.iter.tail]
return bytes.NewReader(remaining)
}
// UseNumber causes the Decoder to unmarshal a number into an interface{} as a
// Number instead of as a float64.
func (adapter *Decoder) UseNumber() {
cfg := adapter.iter.cfg.configBeforeFrozen
cfg.UseNumber = true
adapter.iter.cfg = cfg.frozeWithCacheReuse(adapter.iter.cfg.extraExtensions)
}
// DisallowUnknownFields causes the Decoder to return an error when the destination
// is a struct and the input contains object keys which do not match any
// non-ignored, exported fields in the destination.
func (adapter *Decoder) DisallowUnknownFields() {
cfg := adapter.iter.cfg.configBeforeFrozen
cfg.DisallowUnknownFields = true
adapter.iter.cfg = cfg.frozeWithCacheReuse(adapter.iter.cfg.extraExtensions)
}
// NewEncoder same as json.NewEncoder
func NewEncoder(writer io.Writer) *Encoder {
return ConfigDefault.NewEncoder(writer)
}
// Encoder same as json.Encoder
type Encoder struct {
stream *Stream
}
// Encode encode interface{} as JSON to io.Writer
func (adapter *Encoder) Encode(val interface{}) error {
adapter.stream.WriteVal(val)
adapter.stream.WriteRaw("\n")
adapter.stream.Flush()
return adapter.stream.Error
}
// SetIndent set the indention. Prefix is not supported
func (adapter *Encoder) SetIndent(prefix, indent string) {
config := adapter.stream.cfg.configBeforeFrozen
config.IndentionStep = len(indent)
adapter.stream.cfg = config.frozeWithCacheReuse(adapter.stream.cfg.extraExtensions)
}
// SetEscapeHTML escape html by default, set to false to disable
func (adapter *Encoder) SetEscapeHTML(escapeHTML bool) {
config := adapter.stream.cfg.configBeforeFrozen
config.EscapeHTML = escapeHTML
adapter.stream.cfg = config.frozeWithCacheReuse(adapter.stream.cfg.extraExtensions)
}
// Valid reports whether data is a valid JSON encoding.
func Valid(data []byte) bool {
return ConfigDefault.Valid(data)
}

View File

@ -1,325 +0,0 @@
package jsoniter
import (
"errors"
"fmt"
"github.com/modern-go/reflect2"
"io"
"reflect"
"strconv"
"unsafe"
)
// Any generic object representation.
// The lazy json implementation holds []byte and parse lazily.
type Any interface {
LastError() error
ValueType() ValueType
MustBeValid() Any
ToBool() bool
ToInt() int
ToInt32() int32
ToInt64() int64
ToUint() uint
ToUint32() uint32
ToUint64() uint64
ToFloat32() float32
ToFloat64() float64
ToString() string
ToVal(val interface{})
Get(path ...interface{}) Any
Size() int
Keys() []string
GetInterface() interface{}
WriteTo(stream *Stream)
}
type baseAny struct{}
func (any *baseAny) Get(path ...interface{}) Any {
return &invalidAny{baseAny{}, fmt.Errorf("GetIndex %v from simple value", path)}
}
func (any *baseAny) Size() int {
return 0
}
func (any *baseAny) Keys() []string {
return []string{}
}
func (any *baseAny) ToVal(obj interface{}) {
panic("not implemented")
}
// WrapInt32 turn int32 into Any interface
func WrapInt32(val int32) Any {
return &int32Any{baseAny{}, val}
}
// WrapInt64 turn int64 into Any interface
func WrapInt64(val int64) Any {
return &int64Any{baseAny{}, val}
}
// WrapUint32 turn uint32 into Any interface
func WrapUint32(val uint32) Any {
return &uint32Any{baseAny{}, val}
}
// WrapUint64 turn uint64 into Any interface
func WrapUint64(val uint64) Any {
return &uint64Any{baseAny{}, val}
}
// WrapFloat64 turn float64 into Any interface
func WrapFloat64(val float64) Any {
return &floatAny{baseAny{}, val}
}
// WrapString turn string into Any interface
func WrapString(val string) Any {
return &stringAny{baseAny{}, val}
}
// Wrap turn a go object into Any interface
func Wrap(val interface{}) Any {
if val == nil {
return &nilAny{}
}
asAny, isAny := val.(Any)
if isAny {
return asAny
}
typ := reflect2.TypeOf(val)
switch typ.Kind() {
case reflect.Slice:
return wrapArray(val)
case reflect.Struct:
return wrapStruct(val)
case reflect.Map:
return wrapMap(val)
case reflect.String:
return WrapString(val.(string))
case reflect.Int:
if strconv.IntSize == 32 {
return WrapInt32(int32(val.(int)))
}
return WrapInt64(int64(val.(int)))
case reflect.Int8:
return WrapInt32(int32(val.(int8)))
case reflect.Int16:
return WrapInt32(int32(val.(int16)))
case reflect.Int32:
return WrapInt32(val.(int32))
case reflect.Int64:
return WrapInt64(val.(int64))
case reflect.Uint:
if strconv.IntSize == 32 {
return WrapUint32(uint32(val.(uint)))
}
return WrapUint64(uint64(val.(uint)))
case reflect.Uintptr:
if ptrSize == 32 {
return WrapUint32(uint32(val.(uintptr)))
}
return WrapUint64(uint64(val.(uintptr)))
case reflect.Uint8:
return WrapUint32(uint32(val.(uint8)))
case reflect.Uint16:
return WrapUint32(uint32(val.(uint16)))
case reflect.Uint32:
return WrapUint32(uint32(val.(uint32)))
case reflect.Uint64:
return WrapUint64(val.(uint64))
case reflect.Float32:
return WrapFloat64(float64(val.(float32)))
case reflect.Float64:
return WrapFloat64(val.(float64))
case reflect.Bool:
if val.(bool) == true {
return &trueAny{}
}
return &falseAny{}
}
return &invalidAny{baseAny{}, fmt.Errorf("unsupported type: %v", typ)}
}
// ReadAny read next JSON element as an Any object. It is a better json.RawMessage.
func (iter *Iterator) ReadAny() Any {
return iter.readAny()
}
func (iter *Iterator) readAny() Any {
c := iter.nextToken()
switch c {
case '"':
iter.unreadByte()
return &stringAny{baseAny{}, iter.ReadString()}
case 'n':
iter.skipThreeBytes('u', 'l', 'l') // null
return &nilAny{}
case 't':
iter.skipThreeBytes('r', 'u', 'e') // true
return &trueAny{}
case 'f':
iter.skipFourBytes('a', 'l', 's', 'e') // false
return &falseAny{}
case '{':
return iter.readObjectAny()
case '[':
return iter.readArrayAny()
case '-':
return iter.readNumberAny(false)
case 0:
return &invalidAny{baseAny{}, errors.New("input is empty")}
default:
return iter.readNumberAny(true)
}
}
func (iter *Iterator) readNumberAny(positive bool) Any {
iter.startCapture(iter.head - 1)
iter.skipNumber()
lazyBuf := iter.stopCapture()
return &numberLazyAny{baseAny{}, iter.cfg, lazyBuf, nil}
}
func (iter *Iterator) readObjectAny() Any {
iter.startCapture(iter.head - 1)
iter.skipObject()
lazyBuf := iter.stopCapture()
return &objectLazyAny{baseAny{}, iter.cfg, lazyBuf, nil}
}
func (iter *Iterator) readArrayAny() Any {
iter.startCapture(iter.head - 1)
iter.skipArray()
lazyBuf := iter.stopCapture()
return &arrayLazyAny{baseAny{}, iter.cfg, lazyBuf, nil}
}
func locateObjectField(iter *Iterator, target string) []byte {
var found []byte
iter.ReadObjectCB(func(iter *Iterator, field string) bool {
if field == target {
found = iter.SkipAndReturnBytes()
return false
}
iter.Skip()
return true
})
return found
}
func locateArrayElement(iter *Iterator, target int) []byte {
var found []byte
n := 0
iter.ReadArrayCB(func(iter *Iterator) bool {
if n == target {
found = iter.SkipAndReturnBytes()
return false
}
iter.Skip()
n++
return true
})
return found
}
func locatePath(iter *Iterator, path []interface{}) Any {
for i, pathKeyObj := range path {
switch pathKey := pathKeyObj.(type) {
case string:
valueBytes := locateObjectField(iter, pathKey)
if valueBytes == nil {
return newInvalidAny(path[i:])
}
iter.ResetBytes(valueBytes)
case int:
valueBytes := locateArrayElement(iter, pathKey)
if valueBytes == nil {
return newInvalidAny(path[i:])
}
iter.ResetBytes(valueBytes)
case int32:
if '*' == pathKey {
return iter.readAny().Get(path[i:]...)
}
return newInvalidAny(path[i:])
default:
return newInvalidAny(path[i:])
}
}
if iter.Error != nil && iter.Error != io.EOF {
return &invalidAny{baseAny{}, iter.Error}
}
return iter.readAny()
}
var anyType = reflect2.TypeOfPtr((*Any)(nil)).Elem()
func createDecoderOfAny(ctx *ctx, typ reflect2.Type) ValDecoder {
if typ == anyType {
return &directAnyCodec{}
}
if typ.Implements(anyType) {
return &anyCodec{
valType: typ,
}
}
return nil
}
func createEncoderOfAny(ctx *ctx, typ reflect2.Type) ValEncoder {
if typ == anyType {
return &directAnyCodec{}
}
if typ.Implements(anyType) {
return &anyCodec{
valType: typ,
}
}
return nil
}
type anyCodec struct {
valType reflect2.Type
}
func (codec *anyCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
panic("not implemented")
}
func (codec *anyCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
obj := codec.valType.UnsafeIndirect(ptr)
any := obj.(Any)
any.WriteTo(stream)
}
func (codec *anyCodec) IsEmpty(ptr unsafe.Pointer) bool {
obj := codec.valType.UnsafeIndirect(ptr)
any := obj.(Any)
return any.Size() == 0
}
type directAnyCodec struct {
}
func (codec *directAnyCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
*(*Any)(ptr) = iter.readAny()
}
func (codec *directAnyCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
any := *(*Any)(ptr)
if any == nil {
stream.WriteNil()
return
}
any.WriteTo(stream)
}
func (codec *directAnyCodec) IsEmpty(ptr unsafe.Pointer) bool {
any := *(*Any)(ptr)
return any.Size() == 0
}

View File

@ -1,278 +0,0 @@
package jsoniter
import (
"reflect"
"unsafe"
)
type arrayLazyAny struct {
baseAny
cfg *frozenConfig
buf []byte
err error
}
func (any *arrayLazyAny) ValueType() ValueType {
return ArrayValue
}
func (any *arrayLazyAny) MustBeValid() Any {
return any
}
func (any *arrayLazyAny) LastError() error {
return any.err
}
func (any *arrayLazyAny) ToBool() bool {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
return iter.ReadArray()
}
func (any *arrayLazyAny) ToInt() int {
if any.ToBool() {
return 1
}
return 0
}
func (any *arrayLazyAny) ToInt32() int32 {
if any.ToBool() {
return 1
}
return 0
}
func (any *arrayLazyAny) ToInt64() int64 {
if any.ToBool() {
return 1
}
return 0
}
func (any *arrayLazyAny) ToUint() uint {
if any.ToBool() {
return 1
}
return 0
}
func (any *arrayLazyAny) ToUint32() uint32 {
if any.ToBool() {
return 1
}
return 0
}
func (any *arrayLazyAny) ToUint64() uint64 {
if any.ToBool() {
return 1
}
return 0
}
func (any *arrayLazyAny) ToFloat32() float32 {
if any.ToBool() {
return 1
}
return 0
}
func (any *arrayLazyAny) ToFloat64() float64 {
if any.ToBool() {
return 1
}
return 0
}
func (any *arrayLazyAny) ToString() string {
return *(*string)(unsafe.Pointer(&any.buf))
}
func (any *arrayLazyAny) ToVal(val interface{}) {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
iter.ReadVal(val)
}
func (any *arrayLazyAny) Get(path ...interface{}) Any {
if len(path) == 0 {
return any
}
switch firstPath := path[0].(type) {
case int:
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
valueBytes := locateArrayElement(iter, firstPath)
if valueBytes == nil {
return newInvalidAny(path)
}
iter.ResetBytes(valueBytes)
return locatePath(iter, path[1:])
case int32:
if '*' == firstPath {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
arr := make([]Any, 0)
iter.ReadArrayCB(func(iter *Iterator) bool {
found := iter.readAny().Get(path[1:]...)
if found.ValueType() != InvalidValue {
arr = append(arr, found)
}
return true
})
return wrapArray(arr)
}
return newInvalidAny(path)
default:
return newInvalidAny(path)
}
}
func (any *arrayLazyAny) Size() int {
size := 0
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
iter.ReadArrayCB(func(iter *Iterator) bool {
size++
iter.Skip()
return true
})
return size
}
func (any *arrayLazyAny) WriteTo(stream *Stream) {
stream.Write(any.buf)
}
func (any *arrayLazyAny) GetInterface() interface{} {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
return iter.Read()
}
type arrayAny struct {
baseAny
val reflect.Value
}
func wrapArray(val interface{}) *arrayAny {
return &arrayAny{baseAny{}, reflect.ValueOf(val)}
}
func (any *arrayAny) ValueType() ValueType {
return ArrayValue
}
func (any *arrayAny) MustBeValid() Any {
return any
}
func (any *arrayAny) LastError() error {
return nil
}
func (any *arrayAny) ToBool() bool {
return any.val.Len() != 0
}
func (any *arrayAny) ToInt() int {
if any.val.Len() == 0 {
return 0
}
return 1
}
func (any *arrayAny) ToInt32() int32 {
if any.val.Len() == 0 {
return 0
}
return 1
}
func (any *arrayAny) ToInt64() int64 {
if any.val.Len() == 0 {
return 0
}
return 1
}
func (any *arrayAny) ToUint() uint {
if any.val.Len() == 0 {
return 0
}
return 1
}
func (any *arrayAny) ToUint32() uint32 {
if any.val.Len() == 0 {
return 0
}
return 1
}
func (any *arrayAny) ToUint64() uint64 {
if any.val.Len() == 0 {
return 0
}
return 1
}
func (any *arrayAny) ToFloat32() float32 {
if any.val.Len() == 0 {
return 0
}
return 1
}
func (any *arrayAny) ToFloat64() float64 {
if any.val.Len() == 0 {
return 0
}
return 1
}
func (any *arrayAny) ToString() string {
str, _ := MarshalToString(any.val.Interface())
return str
}
func (any *arrayAny) Get(path ...interface{}) Any {
if len(path) == 0 {
return any
}
switch firstPath := path[0].(type) {
case int:
if firstPath < 0 || firstPath >= any.val.Len() {
return newInvalidAny(path)
}
return Wrap(any.val.Index(firstPath).Interface())
case int32:
if '*' == firstPath {
mappedAll := make([]Any, 0)
for i := 0; i < any.val.Len(); i++ {
mapped := Wrap(any.val.Index(i).Interface()).Get(path[1:]...)
if mapped.ValueType() != InvalidValue {
mappedAll = append(mappedAll, mapped)
}
}
return wrapArray(mappedAll)
}
return newInvalidAny(path)
default:
return newInvalidAny(path)
}
}
func (any *arrayAny) Size() int {
return any.val.Len()
}
func (any *arrayAny) WriteTo(stream *Stream) {
stream.WriteVal(any.val)
}
func (any *arrayAny) GetInterface() interface{} {
return any.val.Interface()
}

View File

@ -1,137 +0,0 @@
package jsoniter
type trueAny struct {
baseAny
}
func (any *trueAny) LastError() error {
return nil
}
func (any *trueAny) ToBool() bool {
return true
}
func (any *trueAny) ToInt() int {
return 1
}
func (any *trueAny) ToInt32() int32 {
return 1
}
func (any *trueAny) ToInt64() int64 {
return 1
}
func (any *trueAny) ToUint() uint {
return 1
}
func (any *trueAny) ToUint32() uint32 {
return 1
}
func (any *trueAny) ToUint64() uint64 {
return 1
}
func (any *trueAny) ToFloat32() float32 {
return 1
}
func (any *trueAny) ToFloat64() float64 {
return 1
}
func (any *trueAny) ToString() string {
return "true"
}
func (any *trueAny) WriteTo(stream *Stream) {
stream.WriteTrue()
}
func (any *trueAny) Parse() *Iterator {
return nil
}
func (any *trueAny) GetInterface() interface{} {
return true
}
func (any *trueAny) ValueType() ValueType {
return BoolValue
}
func (any *trueAny) MustBeValid() Any {
return any
}
type falseAny struct {
baseAny
}
func (any *falseAny) LastError() error {
return nil
}
func (any *falseAny) ToBool() bool {
return false
}
func (any *falseAny) ToInt() int {
return 0
}
func (any *falseAny) ToInt32() int32 {
return 0
}
func (any *falseAny) ToInt64() int64 {
return 0
}
func (any *falseAny) ToUint() uint {
return 0
}
func (any *falseAny) ToUint32() uint32 {
return 0
}
func (any *falseAny) ToUint64() uint64 {
return 0
}
func (any *falseAny) ToFloat32() float32 {
return 0
}
func (any *falseAny) ToFloat64() float64 {
return 0
}
func (any *falseAny) ToString() string {
return "false"
}
func (any *falseAny) WriteTo(stream *Stream) {
stream.WriteFalse()
}
func (any *falseAny) Parse() *Iterator {
return nil
}
func (any *falseAny) GetInterface() interface{} {
return false
}
func (any *falseAny) ValueType() ValueType {
return BoolValue
}
func (any *falseAny) MustBeValid() Any {
return any
}

View File

@ -1,83 +0,0 @@
package jsoniter
import (
"strconv"
)
type floatAny struct {
baseAny
val float64
}
func (any *floatAny) Parse() *Iterator {
return nil
}
func (any *floatAny) ValueType() ValueType {
return NumberValue
}
func (any *floatAny) MustBeValid() Any {
return any
}
func (any *floatAny) LastError() error {
return nil
}
func (any *floatAny) ToBool() bool {
return any.ToFloat64() != 0
}
func (any *floatAny) ToInt() int {
return int(any.val)
}
func (any *floatAny) ToInt32() int32 {
return int32(any.val)
}
func (any *floatAny) ToInt64() int64 {
return int64(any.val)
}
func (any *floatAny) ToUint() uint {
if any.val > 0 {
return uint(any.val)
}
return 0
}
func (any *floatAny) ToUint32() uint32 {
if any.val > 0 {
return uint32(any.val)
}
return 0
}
func (any *floatAny) ToUint64() uint64 {
if any.val > 0 {
return uint64(any.val)
}
return 0
}
func (any *floatAny) ToFloat32() float32 {
return float32(any.val)
}
func (any *floatAny) ToFloat64() float64 {
return any.val
}
func (any *floatAny) ToString() string {
return strconv.FormatFloat(any.val, 'E', -1, 64)
}
func (any *floatAny) WriteTo(stream *Stream) {
stream.WriteFloat64(any.val)
}
func (any *floatAny) GetInterface() interface{} {
return any.val
}

View File

@ -1,74 +0,0 @@
package jsoniter
import (
"strconv"
)
type int32Any struct {
baseAny
val int32
}
func (any *int32Any) LastError() error {
return nil
}
func (any *int32Any) ValueType() ValueType {
return NumberValue
}
func (any *int32Any) MustBeValid() Any {
return any
}
func (any *int32Any) ToBool() bool {
return any.val != 0
}
func (any *int32Any) ToInt() int {
return int(any.val)
}
func (any *int32Any) ToInt32() int32 {
return any.val
}
func (any *int32Any) ToInt64() int64 {
return int64(any.val)
}
func (any *int32Any) ToUint() uint {
return uint(any.val)
}
func (any *int32Any) ToUint32() uint32 {
return uint32(any.val)
}
func (any *int32Any) ToUint64() uint64 {
return uint64(any.val)
}
func (any *int32Any) ToFloat32() float32 {
return float32(any.val)
}
func (any *int32Any) ToFloat64() float64 {
return float64(any.val)
}
func (any *int32Any) ToString() string {
return strconv.FormatInt(int64(any.val), 10)
}
func (any *int32Any) WriteTo(stream *Stream) {
stream.WriteInt32(any.val)
}
func (any *int32Any) Parse() *Iterator {
return nil
}
func (any *int32Any) GetInterface() interface{} {
return any.val
}

View File

@ -1,74 +0,0 @@
package jsoniter
import (
"strconv"
)
type int64Any struct {
baseAny
val int64
}
func (any *int64Any) LastError() error {
return nil
}
func (any *int64Any) ValueType() ValueType {
return NumberValue
}
func (any *int64Any) MustBeValid() Any {
return any
}
func (any *int64Any) ToBool() bool {
return any.val != 0
}
func (any *int64Any) ToInt() int {
return int(any.val)
}
func (any *int64Any) ToInt32() int32 {
return int32(any.val)
}
func (any *int64Any) ToInt64() int64 {
return any.val
}
func (any *int64Any) ToUint() uint {
return uint(any.val)
}
func (any *int64Any) ToUint32() uint32 {
return uint32(any.val)
}
func (any *int64Any) ToUint64() uint64 {
return uint64(any.val)
}
func (any *int64Any) ToFloat32() float32 {
return float32(any.val)
}
func (any *int64Any) ToFloat64() float64 {
return float64(any.val)
}
func (any *int64Any) ToString() string {
return strconv.FormatInt(any.val, 10)
}
func (any *int64Any) WriteTo(stream *Stream) {
stream.WriteInt64(any.val)
}
func (any *int64Any) Parse() *Iterator {
return nil
}
func (any *int64Any) GetInterface() interface{} {
return any.val
}

View File

@ -1,82 +0,0 @@
package jsoniter
import "fmt"
type invalidAny struct {
baseAny
err error
}
func newInvalidAny(path []interface{}) *invalidAny {
return &invalidAny{baseAny{}, fmt.Errorf("%v not found", path)}
}
func (any *invalidAny) LastError() error {
return any.err
}
func (any *invalidAny) ValueType() ValueType {
return InvalidValue
}
func (any *invalidAny) MustBeValid() Any {
panic(any.err)
}
func (any *invalidAny) ToBool() bool {
return false
}
func (any *invalidAny) ToInt() int {
return 0
}
func (any *invalidAny) ToInt32() int32 {
return 0
}
func (any *invalidAny) ToInt64() int64 {
return 0
}
func (any *invalidAny) ToUint() uint {
return 0
}
func (any *invalidAny) ToUint32() uint32 {
return 0
}
func (any *invalidAny) ToUint64() uint64 {
return 0
}
func (any *invalidAny) ToFloat32() float32 {
return 0
}
func (any *invalidAny) ToFloat64() float64 {
return 0
}
func (any *invalidAny) ToString() string {
return ""
}
func (any *invalidAny) WriteTo(stream *Stream) {
}
func (any *invalidAny) Get(path ...interface{}) Any {
if any.err == nil {
return &invalidAny{baseAny{}, fmt.Errorf("get %v from invalid", path)}
}
return &invalidAny{baseAny{}, fmt.Errorf("%v, get %v from invalid", any.err, path)}
}
func (any *invalidAny) Parse() *Iterator {
return nil
}
func (any *invalidAny) GetInterface() interface{} {
return nil
}

View File

@ -1,69 +0,0 @@
package jsoniter
type nilAny struct {
baseAny
}
func (any *nilAny) LastError() error {
return nil
}
func (any *nilAny) ValueType() ValueType {
return NilValue
}
func (any *nilAny) MustBeValid() Any {
return any
}
func (any *nilAny) ToBool() bool {
return false
}
func (any *nilAny) ToInt() int {
return 0
}
func (any *nilAny) ToInt32() int32 {
return 0
}
func (any *nilAny) ToInt64() int64 {
return 0
}
func (any *nilAny) ToUint() uint {
return 0
}
func (any *nilAny) ToUint32() uint32 {
return 0
}
func (any *nilAny) ToUint64() uint64 {
return 0
}
func (any *nilAny) ToFloat32() float32 {
return 0
}
func (any *nilAny) ToFloat64() float64 {
return 0
}
func (any *nilAny) ToString() string {
return ""
}
func (any *nilAny) WriteTo(stream *Stream) {
stream.WriteNil()
}
func (any *nilAny) Parse() *Iterator {
return nil
}
func (any *nilAny) GetInterface() interface{} {
return nil
}

View File

@ -1,123 +0,0 @@
package jsoniter
import (
"io"
"unsafe"
)
type numberLazyAny struct {
baseAny
cfg *frozenConfig
buf []byte
err error
}
func (any *numberLazyAny) ValueType() ValueType {
return NumberValue
}
func (any *numberLazyAny) MustBeValid() Any {
return any
}
func (any *numberLazyAny) LastError() error {
return any.err
}
func (any *numberLazyAny) ToBool() bool {
return any.ToFloat64() != 0
}
func (any *numberLazyAny) ToInt() int {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
val := iter.ReadInt()
if iter.Error != nil && iter.Error != io.EOF {
any.err = iter.Error
}
return val
}
func (any *numberLazyAny) ToInt32() int32 {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
val := iter.ReadInt32()
if iter.Error != nil && iter.Error != io.EOF {
any.err = iter.Error
}
return val
}
func (any *numberLazyAny) ToInt64() int64 {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
val := iter.ReadInt64()
if iter.Error != nil && iter.Error != io.EOF {
any.err = iter.Error
}
return val
}
func (any *numberLazyAny) ToUint() uint {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
val := iter.ReadUint()
if iter.Error != nil && iter.Error != io.EOF {
any.err = iter.Error
}
return val
}
func (any *numberLazyAny) ToUint32() uint32 {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
val := iter.ReadUint32()
if iter.Error != nil && iter.Error != io.EOF {
any.err = iter.Error
}
return val
}
func (any *numberLazyAny) ToUint64() uint64 {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
val := iter.ReadUint64()
if iter.Error != nil && iter.Error != io.EOF {
any.err = iter.Error
}
return val
}
func (any *numberLazyAny) ToFloat32() float32 {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
val := iter.ReadFloat32()
if iter.Error != nil && iter.Error != io.EOF {
any.err = iter.Error
}
return val
}
func (any *numberLazyAny) ToFloat64() float64 {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
val := iter.ReadFloat64()
if iter.Error != nil && iter.Error != io.EOF {
any.err = iter.Error
}
return val
}
func (any *numberLazyAny) ToString() string {
return *(*string)(unsafe.Pointer(&any.buf))
}
func (any *numberLazyAny) WriteTo(stream *Stream) {
stream.Write(any.buf)
}
func (any *numberLazyAny) GetInterface() interface{} {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
return iter.Read()
}

View File

@ -1,374 +0,0 @@
package jsoniter
import (
"reflect"
"unsafe"
)
type objectLazyAny struct {
baseAny
cfg *frozenConfig
buf []byte
err error
}
func (any *objectLazyAny) ValueType() ValueType {
return ObjectValue
}
func (any *objectLazyAny) MustBeValid() Any {
return any
}
func (any *objectLazyAny) LastError() error {
return any.err
}
func (any *objectLazyAny) ToBool() bool {
return true
}
func (any *objectLazyAny) ToInt() int {
return 0
}
func (any *objectLazyAny) ToInt32() int32 {
return 0
}
func (any *objectLazyAny) ToInt64() int64 {
return 0
}
func (any *objectLazyAny) ToUint() uint {
return 0
}
func (any *objectLazyAny) ToUint32() uint32 {
return 0
}
func (any *objectLazyAny) ToUint64() uint64 {
return 0
}
func (any *objectLazyAny) ToFloat32() float32 {
return 0
}
func (any *objectLazyAny) ToFloat64() float64 {
return 0
}
func (any *objectLazyAny) ToString() string {
return *(*string)(unsafe.Pointer(&any.buf))
}
func (any *objectLazyAny) ToVal(obj interface{}) {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
iter.ReadVal(obj)
}
func (any *objectLazyAny) Get(path ...interface{}) Any {
if len(path) == 0 {
return any
}
switch firstPath := path[0].(type) {
case string:
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
valueBytes := locateObjectField(iter, firstPath)
if valueBytes == nil {
return newInvalidAny(path)
}
iter.ResetBytes(valueBytes)
return locatePath(iter, path[1:])
case int32:
if '*' == firstPath {
mappedAll := map[string]Any{}
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
iter.ReadMapCB(func(iter *Iterator, field string) bool {
mapped := locatePath(iter, path[1:])
if mapped.ValueType() != InvalidValue {
mappedAll[field] = mapped
}
return true
})
return wrapMap(mappedAll)
}
return newInvalidAny(path)
default:
return newInvalidAny(path)
}
}
func (any *objectLazyAny) Keys() []string {
keys := []string{}
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
iter.ReadMapCB(func(iter *Iterator, field string) bool {
iter.Skip()
keys = append(keys, field)
return true
})
return keys
}
func (any *objectLazyAny) Size() int {
size := 0
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
iter.ReadObjectCB(func(iter *Iterator, field string) bool {
iter.Skip()
size++
return true
})
return size
}
func (any *objectLazyAny) WriteTo(stream *Stream) {
stream.Write(any.buf)
}
func (any *objectLazyAny) GetInterface() interface{} {
iter := any.cfg.BorrowIterator(any.buf)
defer any.cfg.ReturnIterator(iter)
return iter.Read()
}
type objectAny struct {
baseAny
err error
val reflect.Value
}
func wrapStruct(val interface{}) *objectAny {
return &objectAny{baseAny{}, nil, reflect.ValueOf(val)}
}
func (any *objectAny) ValueType() ValueType {
return ObjectValue
}
func (any *objectAny) MustBeValid() Any {
return any
}
func (any *objectAny) Parse() *Iterator {
return nil
}
func (any *objectAny) LastError() error {
return any.err
}
func (any *objectAny) ToBool() bool {
return any.val.NumField() != 0
}
func (any *objectAny) ToInt() int {
return 0
}
func (any *objectAny) ToInt32() int32 {
return 0
}
func (any *objectAny) ToInt64() int64 {
return 0
}
func (any *objectAny) ToUint() uint {
return 0
}
func (any *objectAny) ToUint32() uint32 {
return 0
}
func (any *objectAny) ToUint64() uint64 {
return 0
}
func (any *objectAny) ToFloat32() float32 {
return 0
}
func (any *objectAny) ToFloat64() float64 {
return 0
}
func (any *objectAny) ToString() string {
str, err := MarshalToString(any.val.Interface())
any.err = err
return str
}
func (any *objectAny) Get(path ...interface{}) Any {
if len(path) == 0 {
return any
}
switch firstPath := path[0].(type) {
case string:
field := any.val.FieldByName(firstPath)
if !field.IsValid() {
return newInvalidAny(path)
}
return Wrap(field.Interface())
case int32:
if '*' == firstPath {
mappedAll := map[string]Any{}
for i := 0; i < any.val.NumField(); i++ {
field := any.val.Field(i)
if field.CanInterface() {
mapped := Wrap(field.Interface()).Get(path[1:]...)
if mapped.ValueType() != InvalidValue {
mappedAll[any.val.Type().Field(i).Name] = mapped
}
}
}
return wrapMap(mappedAll)
}
return newInvalidAny(path)
default:
return newInvalidAny(path)
}
}
func (any *objectAny) Keys() []string {
keys := make([]string, 0, any.val.NumField())
for i := 0; i < any.val.NumField(); i++ {
keys = append(keys, any.val.Type().Field(i).Name)
}
return keys
}
func (any *objectAny) Size() int {
return any.val.NumField()
}
func (any *objectAny) WriteTo(stream *Stream) {
stream.WriteVal(any.val)
}
func (any *objectAny) GetInterface() interface{} {
return any.val.Interface()
}
type mapAny struct {
baseAny
err error
val reflect.Value
}
func wrapMap(val interface{}) *mapAny {
return &mapAny{baseAny{}, nil, reflect.ValueOf(val)}
}
func (any *mapAny) ValueType() ValueType {
return ObjectValue
}
func (any *mapAny) MustBeValid() Any {
return any
}
func (any *mapAny) Parse() *Iterator {
return nil
}
func (any *mapAny) LastError() error {
return any.err
}
func (any *mapAny) ToBool() bool {
return true
}
func (any *mapAny) ToInt() int {
return 0
}
func (any *mapAny) ToInt32() int32 {
return 0
}
func (any *mapAny) ToInt64() int64 {
return 0
}
func (any *mapAny) ToUint() uint {
return 0
}
func (any *mapAny) ToUint32() uint32 {
return 0
}
func (any *mapAny) ToUint64() uint64 {
return 0
}
func (any *mapAny) ToFloat32() float32 {
return 0
}
func (any *mapAny) ToFloat64() float64 {
return 0
}
func (any *mapAny) ToString() string {
str, err := MarshalToString(any.val.Interface())
any.err = err
return str
}
func (any *mapAny) Get(path ...interface{}) Any {
if len(path) == 0 {
return any
}
switch firstPath := path[0].(type) {
case int32:
if '*' == firstPath {
mappedAll := map[string]Any{}
for _, key := range any.val.MapKeys() {
keyAsStr := key.String()
element := Wrap(any.val.MapIndex(key).Interface())
mapped := element.Get(path[1:]...)
if mapped.ValueType() != InvalidValue {
mappedAll[keyAsStr] = mapped
}
}
return wrapMap(mappedAll)
}
return newInvalidAny(path)
default:
value := any.val.MapIndex(reflect.ValueOf(firstPath))
if !value.IsValid() {
return newInvalidAny(path)
}
return Wrap(value.Interface())
}
}
func (any *mapAny) Keys() []string {
keys := make([]string, 0, any.val.Len())
for _, key := range any.val.MapKeys() {
keys = append(keys, key.String())
}
return keys
}
func (any *mapAny) Size() int {
return any.val.Len()
}
func (any *mapAny) WriteTo(stream *Stream) {
stream.WriteVal(any.val)
}
func (any *mapAny) GetInterface() interface{} {
return any.val.Interface()
}

View File

@ -1,166 +0,0 @@
package jsoniter
import (
"fmt"
"strconv"
)
type stringAny struct {
baseAny
val string
}
func (any *stringAny) Get(path ...interface{}) Any {
if len(path) == 0 {
return any
}
return &invalidAny{baseAny{}, fmt.Errorf("GetIndex %v from simple value", path)}
}
func (any *stringAny) Parse() *Iterator {
return nil
}
func (any *stringAny) ValueType() ValueType {
return StringValue
}
func (any *stringAny) MustBeValid() Any {
return any
}
func (any *stringAny) LastError() error {
return nil
}
func (any *stringAny) ToBool() bool {
str := any.ToString()
if str == "0" {
return false
}
for _, c := range str {
switch c {
case ' ', '\n', '\r', '\t':
default:
return true
}
}
return false
}
func (any *stringAny) ToInt() int {
return int(any.ToInt64())
}
func (any *stringAny) ToInt32() int32 {
return int32(any.ToInt64())
}
func (any *stringAny) ToInt64() int64 {
if any.val == "" {
return 0
}
flag := 1
startPos := 0
if any.val[0] == '+' || any.val[0] == '-' {
startPos = 1
}
if any.val[0] == '-' {
flag = -1
}
endPos := startPos
for i := startPos; i < len(any.val); i++ {
if any.val[i] >= '0' && any.val[i] <= '9' {
endPos = i + 1
} else {
break
}
}
parsed, _ := strconv.ParseInt(any.val[startPos:endPos], 10, 64)
return int64(flag) * parsed
}
func (any *stringAny) ToUint() uint {
return uint(any.ToUint64())
}
func (any *stringAny) ToUint32() uint32 {
return uint32(any.ToUint64())
}
func (any *stringAny) ToUint64() uint64 {
if any.val == "" {
return 0
}
startPos := 0
if any.val[0] == '-' {
return 0
}
if any.val[0] == '+' {
startPos = 1
}
endPos := startPos
for i := startPos; i < len(any.val); i++ {
if any.val[i] >= '0' && any.val[i] <= '9' {
endPos = i + 1
} else {
break
}
}
parsed, _ := strconv.ParseUint(any.val[startPos:endPos], 10, 64)
return parsed
}
func (any *stringAny) ToFloat32() float32 {
return float32(any.ToFloat64())
}
func (any *stringAny) ToFloat64() float64 {
if len(any.val) == 0 {
return 0
}
// first char invalid
if any.val[0] != '+' && any.val[0] != '-' && (any.val[0] > '9' || any.val[0] < '0') {
return 0
}
// extract valid num expression from string
// eg 123true => 123, -12.12xxa => -12.12
endPos := 1
for i := 1; i < len(any.val); i++ {
if any.val[i] == '.' || any.val[i] == 'e' || any.val[i] == 'E' || any.val[i] == '+' || any.val[i] == '-' {
endPos = i + 1
continue
}
// end position is the first char which is not digit
if any.val[i] >= '0' && any.val[i] <= '9' {
endPos = i + 1
} else {
endPos = i
break
}
}
parsed, _ := strconv.ParseFloat(any.val[:endPos], 64)
return parsed
}
func (any *stringAny) ToString() string {
return any.val
}
func (any *stringAny) WriteTo(stream *Stream) {
stream.WriteString(any.val)
}
func (any *stringAny) GetInterface() interface{} {
return any.val
}

View File

@ -1,74 +0,0 @@
package jsoniter
import (
"strconv"
)
type uint32Any struct {
baseAny
val uint32
}
func (any *uint32Any) LastError() error {
return nil
}
func (any *uint32Any) ValueType() ValueType {
return NumberValue
}
func (any *uint32Any) MustBeValid() Any {
return any
}
func (any *uint32Any) ToBool() bool {
return any.val != 0
}
func (any *uint32Any) ToInt() int {
return int(any.val)
}
func (any *uint32Any) ToInt32() int32 {
return int32(any.val)
}
func (any *uint32Any) ToInt64() int64 {
return int64(any.val)
}
func (any *uint32Any) ToUint() uint {
return uint(any.val)
}
func (any *uint32Any) ToUint32() uint32 {
return any.val
}
func (any *uint32Any) ToUint64() uint64 {
return uint64(any.val)
}
func (any *uint32Any) ToFloat32() float32 {
return float32(any.val)
}
func (any *uint32Any) ToFloat64() float64 {
return float64(any.val)
}
func (any *uint32Any) ToString() string {
return strconv.FormatInt(int64(any.val), 10)
}
func (any *uint32Any) WriteTo(stream *Stream) {
stream.WriteUint32(any.val)
}
func (any *uint32Any) Parse() *Iterator {
return nil
}
func (any *uint32Any) GetInterface() interface{} {
return any.val
}

View File

@ -1,74 +0,0 @@
package jsoniter
import (
"strconv"
)
type uint64Any struct {
baseAny
val uint64
}
func (any *uint64Any) LastError() error {
return nil
}
func (any *uint64Any) ValueType() ValueType {
return NumberValue
}
func (any *uint64Any) MustBeValid() Any {
return any
}
func (any *uint64Any) ToBool() bool {
return any.val != 0
}
func (any *uint64Any) ToInt() int {
return int(any.val)
}
func (any *uint64Any) ToInt32() int32 {
return int32(any.val)
}
func (any *uint64Any) ToInt64() int64 {
return int64(any.val)
}
func (any *uint64Any) ToUint() uint {
return uint(any.val)
}
func (any *uint64Any) ToUint32() uint32 {
return uint32(any.val)
}
func (any *uint64Any) ToUint64() uint64 {
return any.val
}
func (any *uint64Any) ToFloat32() float32 {
return float32(any.val)
}
func (any *uint64Any) ToFloat64() float64 {
return float64(any.val)
}
func (any *uint64Any) ToString() string {
return strconv.FormatUint(any.val, 10)
}
func (any *uint64Any) WriteTo(stream *Stream) {
stream.WriteUint64(any.val)
}
func (any *uint64Any) Parse() *Iterator {
return nil
}
func (any *uint64Any) GetInterface() interface{} {
return any.val
}

View File

@ -1,12 +0,0 @@
#!/bin/bash
set -e
set -x
if [ ! -d /tmp/build-golang/src/github.com/json-iterator ]; then
mkdir -p /tmp/build-golang/src/github.com/json-iterator
ln -s $PWD /tmp/build-golang/src/github.com/json-iterator/go
fi
export GOPATH=/tmp/build-golang
go get -u github.com/golang/dep/cmd/dep
cd /tmp/build-golang/src/github.com/json-iterator/go
exec $GOPATH/bin/dep ensure -update

View File

@ -1,375 +0,0 @@
package jsoniter
import (
"encoding/json"
"io"
"reflect"
"sync"
"unsafe"
"github.com/modern-go/concurrent"
"github.com/modern-go/reflect2"
)
// Config customize how the API should behave.
// The API is created from Config by Froze.
type Config struct {
IndentionStep int
MarshalFloatWith6Digits bool
EscapeHTML bool
SortMapKeys bool
UseNumber bool
DisallowUnknownFields bool
TagKey string
OnlyTaggedField bool
ValidateJsonRawMessage bool
ObjectFieldMustBeSimpleString bool
CaseSensitive bool
}
// API the public interface of this package.
// Primary Marshal and Unmarshal.
type API interface {
IteratorPool
StreamPool
MarshalToString(v interface{}) (string, error)
Marshal(v interface{}) ([]byte, error)
MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
UnmarshalFromString(str string, v interface{}) error
Unmarshal(data []byte, v interface{}) error
Get(data []byte, path ...interface{}) Any
NewEncoder(writer io.Writer) *Encoder
NewDecoder(reader io.Reader) *Decoder
Valid(data []byte) bool
RegisterExtension(extension Extension)
DecoderOf(typ reflect2.Type) ValDecoder
EncoderOf(typ reflect2.Type) ValEncoder
}
// ConfigDefault the default API
var ConfigDefault = Config{
EscapeHTML: true,
}.Froze()
// ConfigCompatibleWithStandardLibrary tries to be 100% compatible with standard library behavior
var ConfigCompatibleWithStandardLibrary = Config{
EscapeHTML: true,
SortMapKeys: true,
ValidateJsonRawMessage: true,
}.Froze()
// ConfigFastest marshals float with only 6 digits precision
var ConfigFastest = Config{
EscapeHTML: false,
MarshalFloatWith6Digits: true, // will lose precession
ObjectFieldMustBeSimpleString: true, // do not unescape object field
}.Froze()
type frozenConfig struct {
configBeforeFrozen Config
sortMapKeys bool
indentionStep int
objectFieldMustBeSimpleString bool
onlyTaggedField bool
disallowUnknownFields bool
decoderCache *concurrent.Map
encoderCache *concurrent.Map
encoderExtension Extension
decoderExtension Extension
extraExtensions []Extension
streamPool *sync.Pool
iteratorPool *sync.Pool
caseSensitive bool
}
func (cfg *frozenConfig) initCache() {
cfg.decoderCache = concurrent.NewMap()
cfg.encoderCache = concurrent.NewMap()
}
func (cfg *frozenConfig) addDecoderToCache(cacheKey uintptr, decoder ValDecoder) {
cfg.decoderCache.Store(cacheKey, decoder)
}
func (cfg *frozenConfig) addEncoderToCache(cacheKey uintptr, encoder ValEncoder) {
cfg.encoderCache.Store(cacheKey, encoder)
}
func (cfg *frozenConfig) getDecoderFromCache(cacheKey uintptr) ValDecoder {
decoder, found := cfg.decoderCache.Load(cacheKey)
if found {
return decoder.(ValDecoder)
}
return nil
}
func (cfg *frozenConfig) getEncoderFromCache(cacheKey uintptr) ValEncoder {
encoder, found := cfg.encoderCache.Load(cacheKey)
if found {
return encoder.(ValEncoder)
}
return nil
}
var cfgCache = concurrent.NewMap()
func getFrozenConfigFromCache(cfg Config) *frozenConfig {
obj, found := cfgCache.Load(cfg)
if found {
return obj.(*frozenConfig)
}
return nil
}
func addFrozenConfigToCache(cfg Config, frozenConfig *frozenConfig) {
cfgCache.Store(cfg, frozenConfig)
}
// Froze forge API from config
func (cfg Config) Froze() API {
api := &frozenConfig{
sortMapKeys: cfg.SortMapKeys,
indentionStep: cfg.IndentionStep,
objectFieldMustBeSimpleString: cfg.ObjectFieldMustBeSimpleString,
onlyTaggedField: cfg.OnlyTaggedField,
disallowUnknownFields: cfg.DisallowUnknownFields,
caseSensitive: cfg.CaseSensitive,
}
api.streamPool = &sync.Pool{
New: func() interface{} {
return NewStream(api, nil, 512)
},
}
api.iteratorPool = &sync.Pool{
New: func() interface{} {
return NewIterator(api)
},
}
api.initCache()
encoderExtension := EncoderExtension{}
decoderExtension := DecoderExtension{}
if cfg.MarshalFloatWith6Digits {
api.marshalFloatWith6Digits(encoderExtension)
}
if cfg.EscapeHTML {
api.escapeHTML(encoderExtension)
}
if cfg.UseNumber {
api.useNumber(decoderExtension)
}
if cfg.ValidateJsonRawMessage {
api.validateJsonRawMessage(encoderExtension)
}
api.encoderExtension = encoderExtension
api.decoderExtension = decoderExtension
api.configBeforeFrozen = cfg
return api
}
func (cfg Config) frozeWithCacheReuse(extraExtensions []Extension) *frozenConfig {
api := getFrozenConfigFromCache(cfg)
if api != nil {
return api
}
api = cfg.Froze().(*frozenConfig)
for _, extension := range extraExtensions {
api.RegisterExtension(extension)
}
addFrozenConfigToCache(cfg, api)
return api
}
func (cfg *frozenConfig) validateJsonRawMessage(extension EncoderExtension) {
encoder := &funcEncoder{func(ptr unsafe.Pointer, stream *Stream) {
rawMessage := *(*json.RawMessage)(ptr)
iter := cfg.BorrowIterator([]byte(rawMessage))
defer cfg.ReturnIterator(iter)
iter.Read()
if iter.Error != nil && iter.Error != io.EOF {
stream.WriteRaw("null")
} else {
stream.WriteRaw(string(rawMessage))
}
}, func(ptr unsafe.Pointer) bool {
return len(*((*json.RawMessage)(ptr))) == 0
}}
extension[reflect2.TypeOfPtr((*json.RawMessage)(nil)).Elem()] = encoder
extension[reflect2.TypeOfPtr((*RawMessage)(nil)).Elem()] = encoder
}
func (cfg *frozenConfig) useNumber(extension DecoderExtension) {
extension[reflect2.TypeOfPtr((*interface{})(nil)).Elem()] = &funcDecoder{func(ptr unsafe.Pointer, iter *Iterator) {
exitingValue := *((*interface{})(ptr))
if exitingValue != nil && reflect.TypeOf(exitingValue).Kind() == reflect.Ptr {
iter.ReadVal(exitingValue)
return
}
if iter.WhatIsNext() == NumberValue {
*((*interface{})(ptr)) = json.Number(iter.readNumberAsString())
} else {
*((*interface{})(ptr)) = iter.Read()
}
}}
}
func (cfg *frozenConfig) getTagKey() string {
tagKey := cfg.configBeforeFrozen.TagKey
if tagKey == "" {
return "json"
}
return tagKey
}
func (cfg *frozenConfig) RegisterExtension(extension Extension) {
cfg.extraExtensions = append(cfg.extraExtensions, extension)
copied := cfg.configBeforeFrozen
cfg.configBeforeFrozen = copied
}
type lossyFloat32Encoder struct {
}
func (encoder *lossyFloat32Encoder) Encode(ptr unsafe.Pointer, stream *Stream) {
stream.WriteFloat32Lossy(*((*float32)(ptr)))
}
func (encoder *lossyFloat32Encoder) IsEmpty(ptr unsafe.Pointer) bool {
return *((*float32)(ptr)) == 0
}
type lossyFloat64Encoder struct {
}
func (encoder *lossyFloat64Encoder) Encode(ptr unsafe.Pointer, stream *Stream) {
stream.WriteFloat64Lossy(*((*float64)(ptr)))
}
func (encoder *lossyFloat64Encoder) IsEmpty(ptr unsafe.Pointer) bool {
return *((*float64)(ptr)) == 0
}
// EnableLossyFloatMarshalling keeps 10**(-6) precision
// for float variables for better performance.
func (cfg *frozenConfig) marshalFloatWith6Digits(extension EncoderExtension) {
// for better performance
extension[reflect2.TypeOfPtr((*float32)(nil)).Elem()] = &lossyFloat32Encoder{}
extension[reflect2.TypeOfPtr((*float64)(nil)).Elem()] = &lossyFloat64Encoder{}
}
type htmlEscapedStringEncoder struct {
}
func (encoder *htmlEscapedStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
str := *((*string)(ptr))
stream.WriteStringWithHTMLEscaped(str)
}
func (encoder *htmlEscapedStringEncoder) IsEmpty(ptr unsafe.Pointer) bool {
return *((*string)(ptr)) == ""
}
func (cfg *frozenConfig) escapeHTML(encoderExtension EncoderExtension) {
encoderExtension[reflect2.TypeOfPtr((*string)(nil)).Elem()] = &htmlEscapedStringEncoder{}
}
func (cfg *frozenConfig) cleanDecoders() {
typeDecoders = map[string]ValDecoder{}
fieldDecoders = map[string]ValDecoder{}
*cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig))
}
func (cfg *frozenConfig) cleanEncoders() {
typeEncoders = map[string]ValEncoder{}
fieldEncoders = map[string]ValEncoder{}
*cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig))
}
func (cfg *frozenConfig) MarshalToString(v interface{}) (string, error) {
stream := cfg.BorrowStream(nil)
defer cfg.ReturnStream(stream)
stream.WriteVal(v)
if stream.Error != nil {
return "", stream.Error
}
return string(stream.Buffer()), nil
}
func (cfg *frozenConfig) Marshal(v interface{}) ([]byte, error) {
stream := cfg.BorrowStream(nil)
defer cfg.ReturnStream(stream)
stream.WriteVal(v)
if stream.Error != nil {
return nil, stream.Error
}
result := stream.Buffer()
copied := make([]byte, len(result))
copy(copied, result)
return copied, nil
}
func (cfg *frozenConfig) MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
if prefix != "" {
panic("prefix is not supported")
}
for _, r := range indent {
if r != ' ' {
panic("indent can only be space")
}
}
newCfg := cfg.configBeforeFrozen
newCfg.IndentionStep = len(indent)
return newCfg.frozeWithCacheReuse(cfg.extraExtensions).Marshal(v)
}
func (cfg *frozenConfig) UnmarshalFromString(str string, v interface{}) error {
data := []byte(str)
iter := cfg.BorrowIterator(data)
defer cfg.ReturnIterator(iter)
iter.ReadVal(v)
c := iter.nextToken()
if c == 0 {
if iter.Error == io.EOF {
return nil
}
return iter.Error
}
iter.ReportError("Unmarshal", "there are bytes left after unmarshal")
return iter.Error
}
func (cfg *frozenConfig) Get(data []byte, path ...interface{}) Any {
iter := cfg.BorrowIterator(data)
defer cfg.ReturnIterator(iter)
return locatePath(iter, path)
}
func (cfg *frozenConfig) Unmarshal(data []byte, v interface{}) error {
iter := cfg.BorrowIterator(data)
defer cfg.ReturnIterator(iter)
iter.ReadVal(v)
c := iter.nextToken()
if c == 0 {
if iter.Error == io.EOF {
return nil
}
return iter.Error
}
iter.ReportError("Unmarshal", "there are bytes left after unmarshal")
return iter.Error
}
func (cfg *frozenConfig) NewEncoder(writer io.Writer) *Encoder {
stream := NewStream(cfg, writer, 512)
return &Encoder{stream}
}
func (cfg *frozenConfig) NewDecoder(reader io.Reader) *Decoder {
iter := Parse(cfg, reader, 512)
return &Decoder{iter}
}
func (cfg *frozenConfig) Valid(data []byte) bool {
iter := cfg.BorrowIterator(data)
defer cfg.ReturnIterator(iter)
iter.Skip()
return iter.Error == nil
}

View File

@ -1,238 +0,0 @@
package extra
import (
"github.com/json-iterator/go"
"github.com/modern-go/reflect2"
"unicode/utf8"
"unsafe"
)
// safeSet holds the value true if the ASCII character with the given array
// position can be represented inside a JSON string without any further
// escaping.
//
// All values are true except for the ASCII control characters (0-31), the
// double quote ("), and the backslash character ("\").
var safeSet = [utf8.RuneSelf]bool{
' ': true,
'!': true,
'"': false,
'#': true,
'$': true,
'%': true,
'&': true,
'\'': true,
'(': true,
')': true,
'*': true,
'+': true,
',': true,
'-': true,
'.': true,
'/': true,
'0': true,
'1': true,
'2': true,
'3': true,
'4': true,
'5': true,
'6': true,
'7': true,
'8': true,
'9': true,
':': true,
';': true,
'<': true,
'=': true,
'>': true,
'?': true,
'@': true,
'A': true,
'B': true,
'C': true,
'D': true,
'E': true,
'F': true,
'G': true,
'H': true,
'I': true,
'J': true,
'K': true,
'L': true,
'M': true,
'N': true,
'O': true,
'P': true,
'Q': true,
'R': true,
'S': true,
'T': true,
'U': true,
'V': true,
'W': true,
'X': true,
'Y': true,
'Z': true,
'[': true,
'\\': false,
']': true,
'^': true,
'_': true,
'`': true,
'a': true,
'b': true,
'c': true,
'd': true,
'e': true,
'f': true,
'g': true,
'h': true,
'i': true,
'j': true,
'k': true,
'l': true,
'm': true,
'n': true,
'o': true,
'p': true,
'q': true,
'r': true,
's': true,
't': true,
'u': true,
'v': true,
'w': true,
'x': true,
'y': true,
'z': true,
'{': true,
'|': true,
'}': true,
'~': true,
'\u007f': true,
}
var binaryType = reflect2.TypeOfPtr((*[]byte)(nil)).Elem()
type BinaryAsStringExtension struct {
jsoniter.DummyExtension
}
func (extension *BinaryAsStringExtension) CreateEncoder(typ reflect2.Type) jsoniter.ValEncoder {
if typ == binaryType {
return &binaryAsStringCodec{}
}
return nil
}
func (extension *BinaryAsStringExtension) CreateDecoder(typ reflect2.Type) jsoniter.ValDecoder {
if typ == binaryType {
return &binaryAsStringCodec{}
}
return nil
}
type binaryAsStringCodec struct {
}
func (codec *binaryAsStringCodec) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
rawBytes := iter.ReadStringAsSlice()
bytes := make([]byte, 0, len(rawBytes))
for i := 0; i < len(rawBytes); i++ {
b := rawBytes[i]
if b == '\\' {
b2 := rawBytes[i+1]
if b2 != '\\' {
iter.ReportError("decode binary as string", `\\x is only supported escape`)
return
}
b3 := rawBytes[i+2]
if b3 != 'x' {
iter.ReportError("decode binary as string", `\\x is only supported escape`)
return
}
b4 := rawBytes[i+3]
b5 := rawBytes[i+4]
i += 4
b = readHex(iter, b4, b5)
}
bytes = append(bytes, b)
}
*(*[]byte)(ptr) = bytes
}
func (codec *binaryAsStringCodec) IsEmpty(ptr unsafe.Pointer) bool {
return len(*((*[]byte)(ptr))) == 0
}
func (codec *binaryAsStringCodec) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
newBuffer := writeBytes(stream.Buffer(), *(*[]byte)(ptr))
stream.SetBuffer(newBuffer)
}
func readHex(iter *jsoniter.Iterator, b1, b2 byte) byte {
var ret byte
if b1 >= '0' && b1 <= '9' {
ret = b1 - '0'
} else if b1 >= 'a' && b1 <= 'f' {
ret = b1 - 'a' + 10
} else {
iter.ReportError("read hex", "expects 0~9 or a~f, but found "+string([]byte{b1}))
return 0
}
ret *= 16
if b2 >= '0' && b2 <= '9' {
ret += b2 - '0'
} else if b2 >= 'a' && b2 <= 'f' {
ret += b2 - 'a' + 10
} else {
iter.ReportError("read hex", "expects 0~9 or a~f, but found "+string([]byte{b2}))
return 0
}
return ret
}
var hex = "0123456789abcdef"
func writeBytes(space []byte, s []byte) []byte {
space = append(space, '"')
// write string, the fast path, without utf8 and escape support
var i int
var c byte
for i, c = range s {
if c < utf8.RuneSelf && safeSet[c] {
space = append(space, c)
} else {
break
}
}
if i == len(s)-1 {
space = append(space, '"')
return space
}
return writeBytesSlowPath(space, s[i:])
}
func writeBytesSlowPath(space []byte, s []byte) []byte {
start := 0
// for the remaining parts, we process them char by char
var i int
var b byte
for i, b = range s {
if b >= utf8.RuneSelf {
space = append(space, '\\', '\\', 'x', hex[b>>4], hex[b&0xF])
start = i + 1
continue
}
if safeSet[b] {
continue
}
if start < i {
space = append(space, s[start:i]...)
}
space = append(space, '\\', '\\', 'x', hex[b>>4], hex[b&0xF])
start = i + 1
}
if start < len(s) {
space = append(space, s[start:]...)
}
return append(space, '"')
}

View File

@ -1,294 +0,0 @@
package extra
import (
"encoding/json"
"io"
"math"
"reflect"
"strings"
"unsafe"
"github.com/json-iterator/go"
"github.com/modern-go/reflect2"
)
const maxUint = ^uint(0)
const maxInt = int(maxUint >> 1)
const minInt = -maxInt - 1
// RegisterFuzzyDecoders decode input from PHP with tolerance.
// It will handle string/number auto conversation, and treat empty [] as empty struct.
func RegisterFuzzyDecoders() {
jsoniter.RegisterExtension(&tolerateEmptyArrayExtension{})
jsoniter.RegisterTypeDecoder("string", &fuzzyStringDecoder{})
jsoniter.RegisterTypeDecoder("float32", &fuzzyFloat32Decoder{})
jsoniter.RegisterTypeDecoder("float64", &fuzzyFloat64Decoder{})
jsoniter.RegisterTypeDecoder("int", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(maxInt) || val < float64(minInt) {
iter.ReportError("fuzzy decode int", "exceed range")
return
}
*((*int)(ptr)) = int(val)
} else {
*((*int)(ptr)) = iter.ReadInt()
}
}})
jsoniter.RegisterTypeDecoder("uint", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(maxUint) || val < 0 {
iter.ReportError("fuzzy decode uint", "exceed range")
return
}
*((*uint)(ptr)) = uint(val)
} else {
*((*uint)(ptr)) = iter.ReadUint()
}
}})
jsoniter.RegisterTypeDecoder("int8", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxInt8) || val < float64(math.MinInt8) {
iter.ReportError("fuzzy decode int8", "exceed range")
return
}
*((*int8)(ptr)) = int8(val)
} else {
*((*int8)(ptr)) = iter.ReadInt8()
}
}})
jsoniter.RegisterTypeDecoder("uint8", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxUint8) || val < 0 {
iter.ReportError("fuzzy decode uint8", "exceed range")
return
}
*((*uint8)(ptr)) = uint8(val)
} else {
*((*uint8)(ptr)) = iter.ReadUint8()
}
}})
jsoniter.RegisterTypeDecoder("int16", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxInt16) || val < float64(math.MinInt16) {
iter.ReportError("fuzzy decode int16", "exceed range")
return
}
*((*int16)(ptr)) = int16(val)
} else {
*((*int16)(ptr)) = iter.ReadInt16()
}
}})
jsoniter.RegisterTypeDecoder("uint16", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxUint16) || val < 0 {
iter.ReportError("fuzzy decode uint16", "exceed range")
return
}
*((*uint16)(ptr)) = uint16(val)
} else {
*((*uint16)(ptr)) = iter.ReadUint16()
}
}})
jsoniter.RegisterTypeDecoder("int32", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxInt32) || val < float64(math.MinInt32) {
iter.ReportError("fuzzy decode int32", "exceed range")
return
}
*((*int32)(ptr)) = int32(val)
} else {
*((*int32)(ptr)) = iter.ReadInt32()
}
}})
jsoniter.RegisterTypeDecoder("uint32", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxUint32) || val < 0 {
iter.ReportError("fuzzy decode uint32", "exceed range")
return
}
*((*uint32)(ptr)) = uint32(val)
} else {
*((*uint32)(ptr)) = iter.ReadUint32()
}
}})
jsoniter.RegisterTypeDecoder("int64", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxInt64) || val < float64(math.MinInt64) {
iter.ReportError("fuzzy decode int64", "exceed range")
return
}
*((*int64)(ptr)) = int64(val)
} else {
*((*int64)(ptr)) = iter.ReadInt64()
}
}})
jsoniter.RegisterTypeDecoder("uint64", &fuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxUint64) || val < 0 {
iter.ReportError("fuzzy decode uint64", "exceed range")
return
}
*((*uint64)(ptr)) = uint64(val)
} else {
*((*uint64)(ptr)) = iter.ReadUint64()
}
}})
}
type tolerateEmptyArrayExtension struct {
jsoniter.DummyExtension
}
func (extension *tolerateEmptyArrayExtension) DecorateDecoder(typ reflect2.Type, decoder jsoniter.ValDecoder) jsoniter.ValDecoder {
if typ.Kind() == reflect.Struct || typ.Kind() == reflect.Map {
return &tolerateEmptyArrayDecoder{decoder}
}
return decoder
}
type tolerateEmptyArrayDecoder struct {
valDecoder jsoniter.ValDecoder
}
func (decoder *tolerateEmptyArrayDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if iter.WhatIsNext() == jsoniter.ArrayValue {
iter.Skip()
newIter := iter.Pool().BorrowIterator([]byte("{}"))
defer iter.Pool().ReturnIterator(newIter)
decoder.valDecoder.Decode(ptr, newIter)
} else {
decoder.valDecoder.Decode(ptr, iter)
}
}
type fuzzyStringDecoder struct {
}
func (decoder *fuzzyStringDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
valueType := iter.WhatIsNext()
switch valueType {
case jsoniter.NumberValue:
var number json.Number
iter.ReadVal(&number)
*((*string)(ptr)) = string(number)
case jsoniter.StringValue:
*((*string)(ptr)) = iter.ReadString()
case jsoniter.NilValue:
iter.Skip()
*((*string)(ptr)) = ""
default:
iter.ReportError("fuzzyStringDecoder", "not number or string")
}
}
type fuzzyIntegerDecoder struct {
fun func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator)
}
func (decoder *fuzzyIntegerDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
valueType := iter.WhatIsNext()
var str string
switch valueType {
case jsoniter.NumberValue:
var number json.Number
iter.ReadVal(&number)
str = string(number)
case jsoniter.StringValue:
str = iter.ReadString()
case jsoniter.BoolValue:
if iter.ReadBool() {
str = "1"
} else {
str = "0"
}
case jsoniter.NilValue:
iter.Skip()
str = "0"
default:
iter.ReportError("fuzzyIntegerDecoder", "not number or string")
}
if len(str) == 0 {
str = "0"
}
newIter := iter.Pool().BorrowIterator([]byte(str))
defer iter.Pool().ReturnIterator(newIter)
isFloat := strings.IndexByte(str, '.') != -1
decoder.fun(isFloat, ptr, newIter)
if newIter.Error != nil && newIter.Error != io.EOF {
iter.Error = newIter.Error
}
}
type fuzzyFloat32Decoder struct {
}
func (decoder *fuzzyFloat32Decoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
valueType := iter.WhatIsNext()
var str string
switch valueType {
case jsoniter.NumberValue:
*((*float32)(ptr)) = iter.ReadFloat32()
case jsoniter.StringValue:
str = iter.ReadString()
newIter := iter.Pool().BorrowIterator([]byte(str))
defer iter.Pool().ReturnIterator(newIter)
*((*float32)(ptr)) = newIter.ReadFloat32()
if newIter.Error != nil && newIter.Error != io.EOF {
iter.Error = newIter.Error
}
case jsoniter.BoolValue:
// support bool to float32
if iter.ReadBool() {
*((*float32)(ptr)) = 1
} else {
*((*float32)(ptr)) = 0
}
case jsoniter.NilValue:
iter.Skip()
*((*float32)(ptr)) = 0
default:
iter.ReportError("fuzzyFloat32Decoder", "not number or string")
}
}
type fuzzyFloat64Decoder struct {
}
func (decoder *fuzzyFloat64Decoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
valueType := iter.WhatIsNext()
var str string
switch valueType {
case jsoniter.NumberValue:
*((*float64)(ptr)) = iter.ReadFloat64()
case jsoniter.StringValue:
str = iter.ReadString()
newIter := iter.Pool().BorrowIterator([]byte(str))
defer iter.Pool().ReturnIterator(newIter)
*((*float64)(ptr)) = newIter.ReadFloat64()
if newIter.Error != nil && newIter.Error != io.EOF {
iter.Error = newIter.Error
}
case jsoniter.BoolValue:
// support bool to float64
if iter.ReadBool() {
*((*float64)(ptr)) = 1
} else {
*((*float64)(ptr)) = 0
}
case jsoniter.NilValue:
iter.Skip()
*((*float64)(ptr)) = 0
default:
iter.ReportError("fuzzyFloat64Decoder", "not number or string")
}
}

View File

@ -1,55 +0,0 @@
package extra
import (
"github.com/json-iterator/go"
"strings"
"unicode"
)
// SetNamingStrategy rename struct fields uniformly
func SetNamingStrategy(translate func(string) string) {
jsoniter.RegisterExtension(&namingStrategyExtension{jsoniter.DummyExtension{}, translate})
}
type namingStrategyExtension struct {
jsoniter.DummyExtension
translate func(string) string
}
func (extension *namingStrategyExtension) UpdateStructDescriptor(structDescriptor *jsoniter.StructDescriptor) {
for _, binding := range structDescriptor.Fields {
if unicode.IsLower(rune(binding.Field.Name()[0])) || binding.Field.Name()[0] == '_'{
continue
}
tag, hastag := binding.Field.Tag().Lookup("json")
if hastag {
tagParts := strings.Split(tag, ",")
if tagParts[0] == "-" {
continue // hidden field
}
if tagParts[0] != "" {
continue // field explicitly named
}
}
binding.ToNames = []string{extension.translate(binding.Field.Name())}
binding.FromNames = []string{extension.translate(binding.Field.Name())}
}
}
// LowerCaseWithUnderscores one strategy to SetNamingStrategy for. It will change HelloWorld to hello_world.
func LowerCaseWithUnderscores(name string) string {
newName := []rune{}
for i, c := range name {
if i == 0 {
newName = append(newName, unicode.ToLower(c))
} else {
if unicode.IsUpper(c) {
newName = append(newName, '_')
newName = append(newName, unicode.ToLower(c))
} else {
newName = append(newName, c)
}
}
}
return string(newName)
}

View File

@ -1,54 +0,0 @@
package extra
import (
"github.com/json-iterator/go"
"strings"
"unicode"
)
// SupportPrivateFields include private fields when encoding/decoding
func SupportPrivateFields() {
jsoniter.RegisterExtension(&privateFieldsExtension{})
}
type privateFieldsExtension struct {
jsoniter.DummyExtension
}
func (extension *privateFieldsExtension) UpdateStructDescriptor(structDescriptor *jsoniter.StructDescriptor) {
for _, binding := range structDescriptor.Fields {
isPrivate := unicode.IsLower(rune(binding.Field.Name()[0]))
if isPrivate {
tag, hastag := binding.Field.Tag().Lookup("json")
if !hastag {
binding.FromNames = []string{binding.Field.Name()}
binding.ToNames = []string{binding.Field.Name()}
continue
}
tagParts := strings.Split(tag, ",")
names := calcFieldNames(binding.Field.Name(), tagParts[0], tag)
binding.FromNames = names
binding.ToNames = names
}
}
}
func calcFieldNames(originalFieldName string, tagProvidedFieldName string, wholeTag string) []string {
// ignore?
if wholeTag == "-" {
return []string{}
}
// rename?
var fieldNames []string
if tagProvidedFieldName == "" {
fieldNames = []string{originalFieldName}
} else {
fieldNames = []string{tagProvidedFieldName}
}
// private?
isNotExported := unicode.IsLower(rune(originalFieldName[0]))
if isNotExported {
fieldNames = []string{}
}
return fieldNames
}

View File

@ -1,31 +0,0 @@
package extra
import (
"github.com/json-iterator/go"
"time"
"unsafe"
)
// RegisterTimeAsInt64Codec encode/decode time since number of unit since epoch. the precision is the unit.
func RegisterTimeAsInt64Codec(precision time.Duration) {
jsoniter.RegisterTypeEncoder("time.Time", &timeAsInt64Codec{precision})
jsoniter.RegisterTypeDecoder("time.Time", &timeAsInt64Codec{precision})
}
type timeAsInt64Codec struct {
precision time.Duration
}
func (codec *timeAsInt64Codec) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
nanoseconds := iter.ReadInt64() * codec.precision.Nanoseconds()
*((*time.Time)(ptr)) = time.Unix(0, nanoseconds)
}
func (codec *timeAsInt64Codec) IsEmpty(ptr unsafe.Pointer) bool {
ts := *((*time.Time)(ptr))
return ts.UnixNano() == 0
}
func (codec *timeAsInt64Codec) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
ts := *((*time.Time)(ptr))
stream.WriteInt64(ts.UnixNano() / codec.precision.Nanoseconds())
}

View File

@ -1,7 +0,0 @@
| json type \ dest type | bool | int | uint | float |string|
| --- | --- | --- | --- |--|--|
| number | positive => true <br/> negative => true <br/> zero => false| 23.2 => 23 <br/> -32.1 => -32| 12.1 => 12 <br/> -12.1 => 0|as normal|same as origin|
| string | empty string => false <br/> string "0" => false <br/> other strings => true | "123.32" => 123 <br/> "-123.4" => -123 <br/> "123.23xxxw" => 123 <br/> "abcde12" => 0 <br/> "-32.1" => -32| 13.2 => 13 <br/> -1.1 => 0 |12.1 => 12.1 <br/> -12.3 => -12.3<br/> 12.4xxa => 12.4 <br/> +1.1e2 =>110 |same as origin|
| bool | true => true <br/> false => false| true => 1 <br/> false => 0 | true => 1 <br/> false => 0 |true => 1 <br/>false => 0|true => "true" <br/> false => "false"|
| object | true | 0 | 0 |0|originnal json|
| array | empty array => false <br/> nonempty array => true| [] => 0 <br/> [1,2] => 1 | [] => 0 <br/> [1,2] => 1 |[] => 0<br/>[1,2] => 1|original json|

Some files were not shown because too many files have changed in this diff Show More