golang 把http封装一下

[复制链接]
1324|4
 楼主| keer_zu 发表于 2018-1-22 17:48 | 显示全部楼层 |阅读模式
本帖最后由 keer_zu 于 2018-1-23 11:00 编辑
  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.     )

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


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

  15. //================================================

  16. type HttpCmd struct {
  17.         //CmdPost(string) (string,error)
  18. }

  19. func (c *HttpCmd)CmdPost(jsonCmd string)([]byte,error) {
  20.         body := jsonCmd
  21.         res, err := http.Post(http_url, "application/json;charset=utf-8", bytes.NewBuffer([]byte(body)))
  22.         if err != nil {
  23.                 fmt.Println("Fatal error ", err.Error())
  24.                 return nil,err
  25.         }

  26.         defer res.Body.Close()

  27.         content, err := ioutil.ReadAll(res.Body)
  28.         if err != nil {
  29.                 fmt.Println("Fatal error ", err.Error())
  30.                 return nil,err
  31.         }

  32.         return content,nil
  33. }

  34. func (c *HttpCmd) CmdParse (res []byte,result interface{}) (ResultComm,error){
  35.         var params ResultComm
  36.         params.SetResult(result)

  37.         if err := jsoniter.Unmarshal(res,&params); err != nil{
  38.                 return params, err
  39.         }

  40.         if params.GetError() != nil{
  41.                 errMsg := fmt.Sprintf("%v", params.GetError())
  42.                 return params, errors.New(errMsg)
  43.         }

  44.         return params, nil
  45. }

  46. //==================================================

  47. type CmdResult interface {
  48.         GetError()*Error
  49.         GetId()int
  50.         GetResult()interface{}
  51.         SetResult(interface{})
  52. }
  53. //////////////////////////////////////////////////////////////////////////////

  54. type CmdAddAsset struct {
  55.         HttpCmd
  56.         ResultComm
  57. }

  58. type AddAssetResul struct {

  59. }


  60. ///////////////////////////////////////////////////////////////////////////////////

  61. type ResultComm struct {
  62.         Err                 *Error                 `json:"error"`
  63.         Result         interface{}         `json:"result"`
  64.         Id                 int                         `json:"id"`
  65. }

  66. func (r *ResultComm)GetError()*Error{
  67.         return r.Err
  68. }

  69. func (r *ResultComm)GetId()int {
  70.         return r.Id
  71. }

  72. func (r *ResultComm)GetResult()interface{}{
  73.         return r.Result
  74. }

  75. func (r *ResultComm)SetResult(result interface{}){
  76.         r.Result = result
  77. }

  78. ///////////////////////////////////////////////////////////////////////////////////


  79. type CmdAddMarket struct {
  80.         HttpCmd
  81.         ResultComm
  82. }

  83. //=======================================================

  84. type CmdMarketSummary struct {
  85.         HttpCmd
  86.         ResultComm
  87. }


  88. type MarketSummaryResult struct {
  89.         Name                 string                 `json:"name"`
  90.         Ask_count         int                         `json:"ask_count"`
  91.         Ask_amount         string                `json:"ask_amount"`
  92.         Bid_count         int                         `json:"bid_count"`
  93.         bid_amount         string                 `json:"bid_amount"`
  94. }


  95. ////////////////////////////////////////////////////////////////////////////////////////

  96. type CommCommand struct {
  97.         HttpCmd
  98.         ResultComm
  99. }
 楼主| keer_zu 发表于 2018-1-22 17:49 | 显示全部楼层
使用:


  1. package main

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



  6. var idCount int = 1


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





  12. func main() {

  13.     fmt.Printf("----")

  14.     // cmdAddAsset := new(api.CmdAddAsset)

  15.     // cmdStr := BuildAssetAddCmd("BBC",20,8)

  16.     // fmt.Printf("@@     %s\n",cmdStr)

  17.     // bd,e := cmdAddAsset.CmdPost(cmdStr)
  18.     // if e != nil {
  19.     //     fmt.Println(e)
  20.     // }

  21.     // fmt.Printf("bd:  %v\n",bd)

  22.     // cmdAddAsset.CmdParse(bd)


  23.     str := "{"method": "market.summary", "params": ["EOSBTC"], "id": 123}"

  24.     cmdMarketSummary  := new(api.CmdMarketSummary)
  25.     bs,es := cmdMarketSummary.CmdPost(str)

  26.     if es != nil {
  27.         fmt.Printf("err: %v \n",es)
  28.         return
  29.     }

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

  31.     var results  []*api.MarketSummaryResult
  32.     //cmdMarketSummary.SetResult(&results)

  33.     cmdMarketSummary.CmdParse(bs,&results)


  34.     //fmt.Printf("result len: %d\n",len(results))
  35.     fmt.Printf("name: %s\n",results[0].Name)
  36.     fmt.Printf("Ask_count: %d\n",results[0].Ask_count)
  37.     fmt.Printf("Ask_amount: %s\n",results[0].Ask_amount)


  38.    


  39. }
gujiamao12345 发表于 2018-1-22 17:58 | 显示全部楼层
版主搞的东西真多
 楼主| keer_zu 发表于 2018-1-23 11:01 | 显示全部楼层

这个做客户端勉强可以,做服务端还不行。尝试一下evio
 楼主| keer_zu 发表于 2018-1-23 15:37 | 显示全部楼层
加上http的get请求:
  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. }
您需要登录后才可以回帖 登录 | 注册

本版积分规则

1488

主题

12949

帖子

55

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