基于之前结果,完成一个简单的测试程序

[复制链接]
1833|11
 楼主| keer_zu 发表于 2018-1-23 23:29 | 显示全部楼层 |阅读模式
cmd.go

  1. package api

  2. import(
  3. "io/ioutil"
  4.     "net/http"
  5.     "bytes"
  6.     jsoniter "github.com/json-iterator/go"
  7.     "fmt"
  8.     "errors"
  9.     "strings"
  10.     )

  11. var http_url string = "http://10.10.1.20:8083"


  12. type Error struct {
  13.         Code         int                 `json:"code"`
  14.         Message         string         `json:"message"`
  15. }

  16. type ApiError struct {
  17.         Error_code         int                 `json:"error_code"`
  18.         Result                 bool         `json:"result"`
  19. }

  20. //type ApiTicker

  21. func TestGetResParse(ret []byte,res interface{}) error{

  22.         var resApi ApiResComm
  23.         resApi.SetRes(res)

  24.         str :=  string(ret[1:len(ret)-1])  //需要正则

  25.         strUn := strings.Replace("{"res":" + str + "}","\","",-1)

  26.         byteUn :=  []byte(strUn)
  27.         fmt.Printf("byteUn: %s\n",byteUn)
  28.        
  29.         if err := jsoniter.Unmarshal(byteUn,&resApi); err != nil{
  30.                 fmt.Printf("parse error: %s\n",err.Error())
  31.                 return err
  32.         }

  33.         return nil
  34. }

  35. //================================================

  36. type HttpCmd struct {
  37.         //CmdPost(string) (string,error)
  38. }

  39. func (c *HttpCmd)CmdPost(jsonCmd string)([]byte,error) {
  40.         body := jsonCmd
  41.         res, err := http.Post(http_url, "application/json;charset=utf-8", bytes.NewBuffer([]byte(body)))
  42.         if err != nil {
  43.                 fmt.Println("http post error ", err.Error())
  44.                 return nil,err
  45.         }

  46.         defer res.Body.Close()

  47.         content, err := ioutil.ReadAll(res.Body)
  48.         if err != nil {
  49.                 fmt.Println("post, read body error ", err.Error())
  50.                 return nil,err
  51.         }

  52.         return content,nil
  53. }

  54. func (c *HttpCmd) CmdGet(getUrl string)([]byte,error) {

  55.         resp, err := http.Get(getUrl)
  56.         if err != nil {
  57.                 fmt.Println("http Get error ", err.Error())
  58.                 return nil,err
  59.         }

  60.         defer resp.Body.Close()
  61.         content, err := ioutil.ReadAll(resp.Body)
  62.         if err != nil {
  63.                 fmt.Println("get, read body error ", err.Error())
  64.                 return nil,err
  65.         }

  66.         return content,nil
  67. }

  68. func (c *HttpCmd) CmdParse (res []byte,result interface{}) (ResultComm,error){
  69.         var params ResultComm
  70.         params.SetResult(result)

  71.         if err := jsoniter.Unmarshal(res,&params); err != nil{
  72.                 return params, err
  73.         }

  74.         if params.GetError() != nil{
  75.                 errMsg := fmt.Sprintf("%v", params.GetError())
  76.                 return params, errors.New(errMsg)
  77.         }

  78.         return params, nil
  79. }

  80. func (c *HttpCmd) ApiResParse(ret []byte,res interface{})(int,error){

  81.         var resApi ApiResComm
  82.          var apiError ApiError
  83.         resApi.SetRes(res)

  84.         str :=  string(ret[1:len(ret)-1])  //需要正则

  85.         strUn := strings.Replace("{"res":" + str + "}","\","",-1)

  86.         strEt := strings.Replace(str,"\","",-1)

  87.         if err := jsoniter.Unmarshal([]byte(strEt),&apiError); err != nil{
  88.                  fmt.Printf("api error parse error: %s\n",err.Error())
  89.                  return 0,err
  90.         }

  91.         byteUn :=  []byte(strUn)
  92.         //fmt.Printf("byteUn: %s\n",byteUn)

  93.         if apiError.Error_code != 0 {
  94.                 return apiError.Error_code,nil
  95.         }
  96.        
  97.         if err := jsoniter.Unmarshal(byteUn,&resApi); err != nil{
  98.                 fmt.Printf("api result parse error: %s\n",err.Error())
  99.                 return 0,err
  100.         }
  101.        
  102.         return 0,nil
  103. }

  104. //==================================================

  105. type CmdResult interface {
  106.         GetError()*Error
  107.         GetId()int
  108.         GetResult()interface{}
  109.         SetResult(interface{})
  110. }


  111. type ApiRes interface {
  112.         GetRes()interface{}
  113.         SetRes(interface{})
  114. }

  115. //////////////////////////////////////////////////////////////////////////////

  116. type CmdAddAsset struct {
  117.         HttpCmd
  118.         ResultComm
  119. }

  120. type AddAssetResul struct {

  121. }


  122. ///////////////////////////////////////////////////////////////////////////////////

  123. type ResultComm struct {
  124.         Err                 *Error                 `json:"error"`
  125.         Result         interface{}         `json:"result"`
  126.         Id                 int                         `json:"id"`
  127. }

  128. func (r *ResultComm)GetError()*Error{
  129.         return r.Err
  130. }

  131. func (r *ResultComm)GetId()int {
  132.         return r.Id
  133. }

  134. func (r *ResultComm)GetResult()interface{}{
  135.         return r.Result
  136. }

  137. func (r *ResultComm)SetResult(result interface{}){
  138.         r.Result = result
  139. }

  140. ///////////////////////////////////////////////////////////////////////////////////

  141. type ApiResComm struct {
  142.         Res         interface{}         `json:"res"`
  143. }

  144. func (r *ApiResComm)GetRes()interface{}{
  145.         return r.Res
  146. }

  147. func (r *ApiResComm)SetRes(res interface{}){
  148.         r.Res = res
  149. }

  150. ///////////////////////////////////////////////////////////////////////////////////


  151. type CmdAddMarket struct {
  152.         HttpCmd
  153.         ResultComm
  154. }

  155. //=======================================================

  156. type CmdMarketSummary struct {
  157.         HttpCmd
  158.         ResultComm
  159. }


  160. type MarketSummaryResult struct {
  161.         Name                 string                 `json:"name"`
  162.         Ask_count         int                         `json:"ask_count"`
  163.         Ask_amount         string                `json:"ask_amount"`
  164.         Bid_count         int                         `json:"bid_count"`
  165.         bid_amount         string                 `json:"bid_amount"`
  166. }


  167. ////////////////////////////////////////////////////////////////////////////////////////

  168. type CommCommand struct {
  169.         HttpCmd
  170.         ResultComm
  171. }


  172. type ApiCommand struct {
  173.         HttpCmd
  174.         ApiResComm
  175. }
 楼主| keer_zu 发表于 2018-1-23 23:30 | 显示全部楼层
api.go


  1. package api

  2. import (
  3.         "fmt"
  4. )

  5. var BaseUrl string  = "http://10.10.1.20:8083/api/v1/"

  6. ///////////////////////////////////////////////// 币币行情 API ////////////////////////////////////////////////////////////

  7. ///////////////////////////////////获取币币行情
  8. func Build_ticker_cmd(market string) string{
  9.         str := BaseUrl + "ticker.do?market=" + market
  10.         return str
  11. }

  12. //// resoponse

  13. type Ticker struct {
  14.         Period         int                 `json:"period"`
  15.         Last         string         `json:"last"`
  16.         Open         string         `json:"open"`
  17.         Close         string         `json:"close"`
  18.         High         string         `json:"high"`
  19.         Low                 string         `json:"low"`
  20.         Volume         string         `json:"volume"`
  21. }

  22. type TickerRes struct {
  23.         Date         string         `json:"date"`
  24.         Tick         *Ticker         `json:"ticker"`
  25. }

  26. ////////////////////////////////////获取深度
  27. func Build_depth_cmd(market string) string{
  28.         str := BaseUrl + "depth.do?market=" + market
  29.         return str
  30. }


  31. type DepthRes struct {
  32.         Asks         [][]float32                 `json:"asks"`
  33.         Bids         [][]float32                 `json:"bids"`
  34. }

  35. /////////////////////////////////////获取交易信息
  36. func Build_trades_cmd(market string,since string) string{
  37.         str := BaseUrl + "trades.do?market=" + market + "&since=" + since
  38.         return str
  39. }



  40. type TradesRes struct {
  41.         Date         string                 `json:"date"`
  42.         Date_ms string                 `json:"date_ms"`
  43.         Price         float32                `json:"price"`
  44.         Amount         float32                 `json:"amount"`
  45.         Tid                 string                 `json:"tid"`
  46.         Type         string                 `json:"type"`
  47. }



  48. ///////////////////////////////////////////////// 币币交易 API //////////////////////////////////////////////////////////////

  49. // ////////////////////////////////////////////获取用户信息

  50. // https://www.hotbit .com/api/v1/userinfo.do?AppKey=Ldwi395y2&Sign=NUhgdi784-dldjt=Ldi
  51. func build_userinfo_cmd(appkey string,sign string) string {
  52.         str := BaseUrl + "userinfo.do?AppKey=" + appkey + "&Sign=" + sign
  53.         return str
  54. }


  55. type Asset struct {
  56.         Available         string                 `json:"available"`
  57.         Freeze                 string                 `json:"freeze"`
  58. }

  59. type UserinfoRes struct {
  60.         Assets                 map[string]Asset         `json:"assets"`
  61.         Error                 string                 `json:"error"`
  62. }


  63. //提交订单
  64. //http://www.hotbit .com/api/v1/trade.do?apikey=e3bdc2ae54f2eb47ec299d830cf0f01c&sign=123&market=EOSUSDT&type=buy&price=200&amount=12.9
  65. func build_trade_cmd(apikey string,sign string,market string,Type string,price string,amount string) string {
  66.         str := BaseUrl + "trade.do?apikey=" + apikey + "&sign=" + sign + "&market=" + market + "&type=" + Type + "&price=" + price + "&amount=" + amount
  67.         return str
  68. }
  69. //{"result":true,"order_id":123456}
  70. type TradeRes struct {
  71.         Result                 bool                 `json:"result"`
  72.         Order_id         int                         `json:"order_id"`
  73. }


  74. ///////////////////////////////////////////////////////////////批量下单
  75. //https://www.hotbit .com/api/v1/batch_trade.do?apikey=e3bdc2ae54f2eb47ec299d830cf0f01c&market=EOSUSDT&type=buy&orders_data=[{price:3,amount:5,type:'sell'},{price:4,amount:6,type:'buy'}]&sign=dkoivndiei
  76. type order_data struct {
  77.         Price         string
  78.         Amount          int
  79.         Type         string
  80. }

  81. func build_batch_trade_cmd(apikey string,sign string,market string,Type string,orders_data []order_data) string {
  82.         str := BaseUrl + "batch_trade.do?apikey=" + apikey + "&sign=" + sign + "&market=" + market + "&type=" + Type + "&orders_data=["
  83.         for i,od := range orders_data {
  84.                 data := fmt.Sprintf("{price:%s,amount:%d,type:'%s'}",od.Price,od.Amount,od.Type)
  85.                 str += data
  86.                 if i < len(orders_data) - 1 {
  87.                         str += ","
  88.                 }
  89.         }

  90.         str += "]"

  91.         return str
  92. }



  93. type OrderRes struct {
  94.         Order_id         int                 `json:"order_id"`
  95.         Error_code         int                 `json:"error_code"`
  96. }


  97. type BatchTradeRes struct {
  98.         Order_info                 []OrderRes         `json:"order_info"`
  99.         Result                         bool                 `json:"result"`
  100. }

  101. //////////////////////////////////////////// 撤销订单 /////////////////////////////////
  102. //https://www.hotbit.com/api/v1/cancel_order.do?apikey=ed47e38a1fdb57e8c28744ecb390c901&market=BTCBCC&order_id=[1231,1232,1233]&sign=meoivn8gjofi9fmbf9rD
  103. func build_cancel_order_cmd(apikey string,sign string,market string,order_id []int) string {
  104.         str := BaseUrl + "cancel_order.do?apikey=" + apikey + "&sign=" + sign + "&market=" + market + "&order_id=["
  105.         for i,id := range order_id {
  106.                 str += fmt.Sprintf("%d",id)
  107.                 if i < len(order_id) - 1 {
  108.                         str += ","
  109.                 }
  110.         }

  111.         str += "]"

  112.         return str
  113. }
  114. //{"success":"123456,123457","error":"123458,123459"}
  115. type CancelOrderRes struct {
  116.         Success                 string                 `json:"success"`
  117.         Error                 string                 `json:"error"`
  118. }


  119. ////////////////////////////////////////////获取用户未完成订单信息
  120. //https://www.hotbit.com/api/v1/order_pending.do?apikey=e3bdc2ae54f2eb47ec299d830cf0f01c&market=EOSUSDT&sign=meoivn8gjofi9fmbf9rD
  121. func build_order_pending_cmd(apikey string,sign string,market string) string {
  122.         str := BaseUrl + "order_pending.do?apikey=" + apikey + "&sign=" + sign + "&market=" + market
  123.         return str
  124. }


  125. type OrderPend struct {
  126.         Id          int                                 `json:"id"`
  127.         Market     string                          `json:"market"`
  128.         source     string                         `json:"source"`
  129.         Type        int                                 `json:"type"`
  130.         Side        int                                 `json:"side"`
  131.         User            int                                 `json:"user"`
  132.         Ctime       float32                           `json:"ctime"`
  133.         Mtime       float32                         `json:"mtime"`
  134.         Price       string                         `json:"price"`
  135.         Amount      string                          `json:"amount"`
  136.         Taker_fee  string                          `json:"maker_fee"`
  137.         Maker_fee  string                         `json:"maker_fee"`
  138.         Left         string                         `json:"left"`
  139.         Deal_stock string                         `json:"deal_stock"`
  140.         Deal_money string                         `json:"deal_money"`
  141.         Deal_fee    string                         `json:"deal_fee"`
  142. }

  143. type OrderPendingRes struct {
  144.         Result                 bool                         `json:"result"`
  145.         Orders                 *OrderPend           `json:"orders"`
  146. }

  147. /////////////////////////////////////////////获取用户已完成订单信息
  148. //https://www.hotbit.com/api/v1/order_finish.do?apikey=e3bdc2ae54f2eb47ec299d830cf0f01c&start_time=152047813&end_time=15204808923&type=sell&market=EOSUSDT&sign=meoivn8gjofi9fmbf9rD
  149. func build_order_finish_cmd(apikey string,sign string,market string,start_time string,end_time string,Type string) string {
  150.         str := BaseUrl + "order_finish.do?apikey=" + apikey + "&sign=" + sign + "&market=" + market + "&start_time=" + start_time + "&end_time=" + end_time + "&type=" + Type
  151.         return str
  152. }

  153. type OrderFinish struct {
  154.         Id          int                                 `json:"id"`
  155.         Ctime       float32                           `json:"ctime"`
  156.         Ftime       float32                         `json:"ftime"`
  157.         User            int                                 `json:"user"`
  158.         Market     string                          `json:"market"`
  159.         source     string                         `json:"source"`
  160.         Type        int                                 `json:"type"`
  161.         Side        int                                 `json:"side"`
  162.         Price       string                         `json:"price"`
  163.         Amount      string                          `json:"amount"`
  164.         Taker_fee  string                          `json:"maker_fee"`
  165.         Maker_fee  string                         `json:"maker_fee"`
  166.         Deal_stock string                         `json:"deal_stock"`
  167.         Deal_money string                         `json:"deal_money"`
  168.         Deal_fee    string                         `json:"deal_fee"`
  169. }

  170. type OrderFinishRes struct {
  171.         Result                 bool                         `json:"result"`
  172.         Orders                 *OrderFinish           `json:"orders"`
  173. }



 楼主| keer_zu 发表于 2018-1-23 23:32 | 显示全部楼层
config.go

读取配置信息:

  1. package utils


  2. import (
  3.         io "io/ioutil"
  4.         json "encoding/json"
  5. )

  6. //////////////////// global /////////////////

  7. var MeCfg *MeConfig

  8. //////////////////////////////////////////////

  9. type Mysql struct {
  10.         Host         string `json:"host"`
  11.         User         string `json:"user"`
  12.         Pass         string `json:"pass"`
  13.         Database        string `json:"database"`
  14.         MaxConn        int        `json:"maxConns"`
  15. }

  16. type Asset struct {
  17.         Name         string                 `json:"name"`
  18.         PrecSave         int                 `json:"prec_save"`
  19.         PrecShow         int                 `json:"prec_show"`
  20. }

  21. type MarketAsset struct {
  22.         Name         string                 `json:"name"`
  23.         Prec         int                         `json:"prec"`
  24. }

  25. type Market struct {
  26.         Name         string                 `json:"name"`
  27.         MinAmount string         `json:"min_amount"`
  28.         Money         *MarketAsset `json:"money"`
  29.         Stock         *MarketAsset `json:"stock"`
  30. }

  31. type Content struct {
  32.         Assets                 []*Asset         `json:"assets"`
  33.         Markets                 []*Market `json:"markets"`
  34. }

  35. type MeConfig struct {
  36.         ErrorCode        int                 `json:"ErrorCode"`               //1100
  37.         ErrorMsg        string         `json:"ErrorMsg"`                //"success"
  38.         Con                         *Content `json:"Content"`
  39. }

  40. type JsonConfig struct {
  41.         BaseUrl                 string          `json:"BaseUrl"`
  42.         MeConfigUrl         string         `json:"MeConfigUrl"`
  43.         Sql                         *Mysql         `json:"Mysql"`
  44. }



  45. type JsonStruct struct{

  46. }


  47. func NewJsonStruct () *JsonStruct {
  48.         return &JsonStruct{}
  49. }


  50. func (self *JsonStruct) Load (filename string, v interface{}) {

  51.         data, err := io.ReadFile(filename)
  52.         if err != nil{
  53.                 return
  54.         }

  55.         datajson := []byte(data)
  56.         err = json.Unmarshal(datajson, v)

  57.         if err != nil{
  58.                 return
  59.         }

  60. }

  61. func (self *JsonStruct) LoadFromString(cfg []byte,v interface{}) {

  62.         err := json.Unmarshal(cfg, v)

  63.         if err != nil{
  64.                 return
  65.         }
  66. }


  67. type ValueTestAtmp struct{

  68.         StringValue string

  69.         NumericalValue int

  70.         BoolValue bool

  71. }


  72. type ConfigData struct {

  73.         ValueTestA ValueTestAtmp

  74. }
 楼主| keer_zu 发表于 2018-1-23 23:33 | 显示全部楼层
get_info.go

从数据库中获取信息

  1. package utils

  2. import (
  3.         "time"
  4.         _ "github.com/go-sql-driver/mysql"
  5.         "github.com/xormplus/xorm"
  6.         "fmt"
  7.         "sync"
  8. )

  9. type Fapi struct {
  10.         Id         int       `xorm:"fid"`
  11.         Fkey        string    `xorm:"fkey"`
  12.         Fsecret     string    `xorm:"fsecret"`
  13.         Fuser       int       `xorm:"fuser"`
  14.         Label       string    `xorm:"label"`
  15.         Fcreatetime time.Time `xorm:"fcreatetime"`
  16.         Fistrade    int       `xorm:"fistrade"`
  17.         Fiswithdraw int       `xorm:"fiswithdraw"`
  18.         Fisreadinfo int       `xorm:"fisreadinfo"`
  19.         Fip         string    `xorm:"fip"`
  20.         WhiteIps    string    `xorm:"whiteIps"`
  21. }

  22. var JsonCfg *JsonConfig

  23. var initEngineOnce sync.Once
  24. var engineMysql *xorm.Engine

  25. func GetEngine(cfg *Mysql)*xorm.Engine{

  26.         initEngineOnce.Do(func(){
  27.                 var err error
  28.                 dbUrl := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8", cfg.User, cfg.Pass, cfg.Host, cfg.Database)
  29.                 //fmt.Printf("\n ***    %s  ***\n",dbUrl)
  30.                 engineMysql, err = xorm.NewEngine("mysql", dbUrl)
  31.                 if err != nil{
  32.                         panic(err)
  33.                 }
  34.                 engineMysql.SetMaxOpenConns(JsonCfg.Sql.MaxConn)
  35.         })

  36.         return engineMysql
  37. }

  38. func GetUserInfo(engine *xorm.Engine)([]Fapi,error) {

  39.         var fapi []Fapi

  40.         if err := engine.Find(&fapi);err != nil {
  41.                 return nil,err
  42.         }

  43.         return fapi,nil
  44. }
 楼主| keer_zu 发表于 2018-1-23 23:33 | 显示全部楼层
main.go

测试用例的实现:

  1. package main

  2. import (
  3.     "fmt"
  4.     "./api"
  5.     "./utils"
  6. )



  7. var idCount int = 1


  8. func BuildAssetAddCmd(name string,prec_save int,prec_show int) string {
  9.     str := fmt.Sprintf("{"method": "asset.add_new","params":["%s",%d,%d],"id":%d}",name,prec_save,prec_show,idCount)
  10.     idCount += 1
  11.     return str
  12. }

  13. func BuildTickerUrl(market string) string{
  14.     str := fmt.Sprintf("http://127.0.0.1:8080/api/v1/ticker.do?market=%s",market)
  15.     return str
  16. }



  17. func main() {

  18.     fmt.Printf("----\n")


  19.     JsonParse := utils.NewJsonStruct()

  20.     //v := utils.JsonConfig{}
  21.     utils.JsonCfg = new(utils.JsonConfig)

  22.     JsonParse.Load("config.json", utils.JsonCfg)
  23.     api.BaseUrl = utils.JsonCfg.BaseUrl

  24.     fmt.Printf("Base Url: %s\n",api.BaseUrl)

  25.     fmt.Println(utils.JsonCfg)

  26.     fmt.Println(utils.JsonCfg.Sql)

  27.     engine := utils.GetEngine(utils.JsonCfg.Sql)

  28.     a,e := utils.GetUserInfo(engine)
  29.     if e == nil {
  30.         for _, v := range a {
  31.             fmt.Println(v)
  32.         }
  33.     }


  34.     apiCmd := new(api.ApiCommand)

  35.     meCfg,e := apiCmd.CmdGet(utils.JsonCfg.MeConfigUrl)

  36.     if e != nil {
  37.         fmt.Printf("meCfg get error\n")
  38.         return
  39.     }

  40.     utils.MeCfg = new(utils.MeConfig)
  41.     JsonParse.LoadFromString(meCfg,utils.MeCfg)

  42.     fmt.Println(utils.MeCfg.Con.Assets[0] )
  43.     fmt.Println(utils.MeCfg.Con.Markets[0].Money )

  44.     ticker := new(api.Ticker)

  45.     for _,market := range utils.MeCfg.Con.Markets {
  46.         str := api.Build_ticker_cmd(market.Name)
  47.         fmt.Printf("url:  %s\n",str)
  48.         bti,et := apiCmd.CmdGet(str)
  49.         if et != nil {
  50.             fmt.Printf("market %s ,ticker get error\n",market.Name)
  51.             continue
  52.         }

  53.         //fmt.Println(bti)

  54.         ecode,err := apiCmd.ApiResParse(bti,ticker)

  55.         if err != nil {
  56.             fmt.Printf("parse error %s\n",err.Error())
  57.             continue
  58.         }

  59.         if ecode != 0 {
  60.             fmt.Printf("api get res err:  %d\n",ecode)
  61.             continue
  62.         }

  63.         fmt.Printf("ticker[%s] = \n%s\n\n",market.Name,bti)
  64.     }

  65.    

  66.    


  67.    //fmt.Printf("meCfg: %s\n",meCfg)


  68.     //fmt.Println(v.ValueTestA .StringValue )

  69.    

  70. /*
  71.     str := "{"method": "market.summary", "params": ["EOSBTC"], "id": 123}"

  72.     cmdMarketSummary  := new(api.CmdMarketSummary)
  73.     bs,es := cmdMarketSummary.CmdPost(str)

  74.     if es != nil {
  75.         fmt.Printf("err: %v \n",es)
  76.         return
  77.     }

  78.     fmt.Printf("bs:  %s\n",bs)

  79.     var results  []*api.MarketSummaryResult
  80.     //cmdMarketSummary.SetResult(&results)

  81.     cmdMarketSummary.CmdParse(bs,&results)


  82.     //fmt.Printf("result len: %d\n",len(results))
  83.     fmt.Printf("name: %s\n",results[0].Name)
  84.     fmt.Printf("Ask_count: %d\n",results[0].Ask_count)
  85.     fmt.Printf("Ask_amount: %s\n",results[0].Ask_amount)

  86.     tickerUrl := BuildTickerUrl("BTC")

  87.     apiCmd := new(api.ApiCommand)

  88.     tres,e := apiCmd.CmdGet(tickerUrl)

  89.     if e != nil {
  90.         fmt.Printf("ticker get error\n")
  91.         return
  92.     }

  93.     fmt.Printf("tres: %s\n",tres)


  94.     var ae api.ApiError

  95.     ecode,err := apiCmd.ApiResParse(tres,&ae)

  96.     if err != nil {
  97.         fmt.Printf("parse error %s\n",err.Error())
  98.         return
  99.     }

  100.     fmt.Printf("Error code: %d\n",ecode)

  101.     if ae.Error_code != 0 {
  102.         fmt.Printf("api get res err:  %d\n",ae.Error_code)
  103.     }
  104. */
  105. }
 楼主| keer_zu 发表于 2018-1-23 23:34 | 显示全部楼层
config.json

配置文件

  1. {
  2.         "MeConfigUrl":"http://10.10.1.20:8080/api/get_config?appname=matchengine_test",
  3.         "BaseUrl":"http://127.0.0.1:8080/api/v1/",
  4.         "mysql":{
  5.       "host":"10.10.1.20:3306",
  6.       "user":"admin",
  7.       "pass":"zxw000123",
  8.       "database":"hotbit_make_web",
  9.       "maxConns":4
  10.     }
  11. }
 楼主| keer_zu 发表于 2018-1-23 23:34 | 显示全部楼层
一天又码了这么多
kelly1989 发表于 2018-1-24 12:39 | 显示全部楼层
厉害了
 楼主| keer_zu 发表于 2018-1-24 23:41 | 显示全部楼层
更多的测试用例:

  1. package main

  2. import (
  3.     "fmt"
  4.     "./api"
  5.     "./utils"
  6.     //"time"
  7. )



  8. var idCount int = 1



  9. func main() {

  10.     fmt.Printf("----\n")


  11.     JsonParse := utils.NewJsonStruct()

  12.     //v := utils.JsonConfig{}
  13.     utils.JsonCfg = new(utils.JsonConfig)

  14.     JsonParse.Load("config.json", utils.JsonCfg)
  15.     api.BaseUrl = utils.JsonCfg.BaseUrl

  16.     //fmt.Printf("Base Url: %s\n",api.BaseUrl)

  17.     //fmt.Println(utils.JsonCfg)

  18.     //fmt.Println(utils.JsonCfg.Sql)

  19.     engine := utils.GetEngine(utils.JsonCfg.Sql)

  20.     a,e := utils.GetUserInfo(engine)
  21.     if e == nil {
  22.         for _, v := range a {
  23.             fmt.Println(v)
  24.         }
  25.     } else {
  26.         fmt.Printf("user info get error\n")
  27.         return
  28.     }


  29.     apiCmd := new(api.ApiCommand)

  30.     meCfg,e := apiCmd.CmdGet(utils.JsonCfg.MeConfigUrl)

  31.     if e != nil {
  32.         fmt.Printf("meCfg get error\n")
  33.         return
  34.     }

  35.     utils.MeCfg = new(utils.MeConfig)
  36.     JsonParse.LoadFromString(meCfg,utils.MeCfg)

  37. //////////////////////////////// trade /////////////////////////////////////
  38. tradeRes := new(api.TradeRes)

  39. Type := "buy"
  40. price := "100"
  41. amount := "10"


  42. for _,market := range utils.MeCfg.Con.Markets {

  43.     for _,v := range a {
  44.         //(apikey string,market string,Type string,price string,amount string)

  45.         params := api.BaseTradeUrl(v.Fkey,market.Name,Type,price,amount)
  46.         if Type == "buy"{
  47.             Type = "sell"
  48.         } else {
  49.             Type = "buy"
  50.         }

  51.         str := api.BaseUrl + params["method?"]

  52.         delete(params,"method?")

  53.         ps := utils.CreatParams(v.Fsecret,params)

  54.         str += ps

  55.         fmt.Printf("url:   %s \n",str)

  56.         bu,e := apiCmd.CmdPost(str)
  57.         if e != nil {
  58.             fmt.Printf("user: %d ,trade error\n",v.Fuser)
  59.             continue
  60.         }

  61.         //fmt.Printf("bu:   %s \n",bu)

  62.         ecode,err := apiCmd.ApiResParse(bu,tradeRes)

  63.         if err != nil {
  64.             fmt.Printf("parse error %s\n",err.Error())
  65.             continue
  66.         }

  67.         if ecode != 0 {
  68.             fmt.Printf("user get info err:  %d\n",ecode)
  69.             continue
  70.         }


  71.         //fmt.Printf("user info[%s] = \n%s\n\n",v.Fuser,bu)

  72.     }
  73. }



  74. ////////////////////////////// balance ////////////////////////////////////
  75. /*      
  76.     userinfoRes := new(api.UserinfoRes)

  77.     for _, v := range a {
  78.         params := make(map[string]string)
  79.         params["apikey"]=v.Fkey
  80.         secKey := v.Fsecret
  81.         fmt.Printf("user:   %d \n",v.Fuser)
  82.         //sign := utils.CreatSign(secKey,params)


  83.         ps := utils.CreatParams(secKey,params)

  84.         str := api.BaseUrl + "balance.do?" + ps//api.Build_userinfo_cmd(v.Fkey,sign)

  85.         fmt.Printf("url:   %s \n",str)


  86.         bu,e := apiCmd.CmdPost(str)
  87.         if e != nil {
  88.             fmt.Printf("user: %d ,info get error\n",v.Fuser)
  89.             continue
  90.         }

  91.         //fmt.Printf("bu:   %s \n",bu)

  92.         ecode,err := apiCmd.ApiResParse(bu,userinfoRes)

  93.         if err != nil {
  94.             fmt.Printf("parse error %s\n",err.Error())
  95.             continue
  96.         }

  97.         if ecode != 0 {
  98.             fmt.Printf("user get info err:  %d\n",ecode)
  99.             continue
  100.         }


  101.         //fmt.Printf("user info[%s] = \n%s\n\n",v.Fuser,bu)

  102.     }

  103.     //fmt.Println(utils.MeCfg.Con.Assets[0] )
  104.     //fmt.Println(utils.MeCfg.Con.Markets[0].Money )


  105. //////////////////////////////// ticker test ///////////////////////////////////

  106.     ticker := new(api.Ticker)

  107.     for _,market := range utils.MeCfg.Con.Markets {
  108.         str := api.Build_ticker_cmd(market.Name)
  109.         fmt.Printf("url:  %s\n",str)
  110.         bti,et := apiCmd.CmdGet(str)
  111.         if et != nil {
  112.             fmt.Printf("market %s ,ticker get error\n",market.Name)
  113.             continue
  114.         }

  115.         //fmt.Println(bti)

  116.         ecode,err := apiCmd.ApiResParse(bti,ticker)

  117.         if err != nil {
  118.             fmt.Printf("parse error %s\n",err.Error())
  119.             continue
  120.         }

  121.         if ecode != 0 {
  122.             fmt.Printf("api get res err:  %d\n",ecode)
  123.             continue
  124.         }

  125.         fmt.Printf("ticker[%s] = \n%s\n\n",market.Name,bti)
  126.     }

  127.     /////////////////////////////////// depth test /////////////////////////

  128.       depth := new(api.DepthRes)

  129.     for _,market := range utils.MeCfg.Con.Markets {
  130.         str := api.Build_depth_cmd(market.Name)
  131.         fmt.Printf("url:  %s\n",str)
  132.         bdp,et := apiCmd.CmdGet(str)
  133.         if et != nil {
  134.             fmt.Printf("market %s ,depth get error\n",market.Name)
  135.             continue
  136.         }

  137.         //fmt.Println(bti)

  138.         ecode,err := apiCmd.ApiResParse(bdp,depth)

  139.         if err != nil {
  140.             fmt.Printf("parse error %s\n",err.Error())
  141.             continue
  142.         }

  143.         if ecode != 0 {
  144.             fmt.Printf("api get res err:  %d\n",ecode)
  145.             continue
  146.         }

  147.         fmt.Printf("depth[%s] = \n%s\n\n",market.Name,bdp)
  148.     }
  149. ////////////////////////////////////////////////////////////////////

  150.     trades := new(api.TradesRes)
  151.      t:=time.Now().Unix()  
  152.      ts := t - 86400
  153.      tss := fmt.Sprintf("%d",ts)

  154.     for _,market := range utils.MeCfg.Con.Markets {
  155.         str := api.Build_trades_cmd(market.Name,tss)
  156.         fmt.Printf("url:  %s\n",str)
  157.         bdp,et := apiCmd.CmdGet(str)
  158.         if et != nil {
  159.             fmt.Printf("market %s ,trades get error\n",market.Name)
  160.             continue
  161.         }

  162.         //fmt.Println(bti)

  163.         ecode,err := apiCmd.ApiResParse(bdp,trades)

  164.         if err != nil {
  165.             fmt.Printf("parse error %s\n",err.Error())
  166.             continue
  167.         }

  168.         if ecode != 0 {
  169.             fmt.Printf("api get res err:  %d\n",ecode)
  170.             continue
  171.         }

  172.         fmt.Printf("trades[%s] = \n%s\n\n",market.Name,bdp)
  173.     }*/

  174. }
msblast 发表于 2018-1-25 09:50 | 显示全部楼层
版主,高大上了……
转战互联网了吗?
 楼主| keer_zu 发表于 2018-1-25 11:25 | 显示全部楼层
msblast 发表于 2018-1-25 09:50
版主,高大上了……
转战互联网了吗?

是的
您需要登录后才可以回帖 登录 | 注册

本版积分规则

1488

主题

12953

帖子

55

粉丝
快速回复 在线客服 返回列表 返回顶部