currency.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package common
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "time"
  8. )
  9. type Status struct {
  10. TimeStamp time.Time `json:"time_stamp,omitempty"`
  11. ErrorCode int `json:"error_code,omitempty"`
  12. ErrorMessage string `json:"error_message,omitempty"`
  13. Elapsed int `json:"elapsed,omitempty"`
  14. CreditCount int `json:"credit_count,omitempty"`
  15. Notice int `json:"notice,omitempty"`
  16. }
  17. type Data struct {
  18. ID int `json:"id,omitempty"`
  19. Symbol string `json:"symbol,omitempty"`
  20. Name string `json:"name,omitempty"`
  21. Amount int `json:"amount,omitempty"`
  22. LastUpdated time.Time `json:"last_updated,omitempty"`
  23. Quote Quote `json:"quote,omitempty"`
  24. }
  25. type DataList struct {
  26. Data [1]Data
  27. }
  28. type Quote struct {
  29. USD PriceSet `json:"usd,omitempty"`
  30. }
  31. type PriceSet struct {
  32. Price float32
  33. LastUpdated time.Time
  34. }
  35. type retSet struct {
  36. Status Status `json:"status,omitempty"`
  37. Data [10]Data `json:"data,omitempty"`
  38. }
  39. func sendPacket(uri string) retSet {
  40. var _r retSet
  41. const headerKey = "X-CMC_PRO_API_KEY"
  42. const apiKey = "4ef32866-4674-412b-9f7f-743c5a75d05c"
  43. req, err := http.NewRequest("GET", uri, nil)
  44. if err != nil {
  45. panic(err)
  46. }
  47. req.Header.Add(headerKey, apiKey)
  48. _client := &http.Client{}
  49. resp, err := _client.Do(req)
  50. if err != nil {
  51. panic(err)
  52. }
  53. bytes, _ := ioutil.ReadAll(resp.Body)
  54. str := string(bytes) //바이트를 문자열로
  55. pb := []byte(str)
  56. fmt.Println(str)
  57. if err := json.Unmarshal(pb, &_r); err != nil {
  58. panic(err)
  59. }
  60. fmt.Printf("data %+v", _r)
  61. defer resp.Body.Close()
  62. return _r
  63. }
  64. func ObtainCurrencyPrice() (float64, float64, float64) {
  65. var uri = "https://pro-api.coinmarketcap.com/v2/tools/price-conversion"
  66. mf1_uri := fmt.Sprintf("%s?amount=1&symbol=MF1", uri)
  67. ret := sendPacket(mf1_uri)
  68. // mf1 = fmt.Sprintf("%f", ret.Data[0].Quote.USD.Price)
  69. mf1 := float64(ret.Data[0].Quote.USD.Price)
  70. mf2_uri := fmt.Sprintf("%s?amount=1&symbol=MF2", uri)
  71. ret = sendPacket(mf2_uri)
  72. // mr, _ := strconv.ParseFloat(fmt.Sprintf("%f", ret.Data[0].Quote.USD.Price), 64)
  73. mr := float64(ret.Data[0].Quote.USD.Price)
  74. eth_uri := fmt.Sprintf("%s?amount=1&symbol=ETH", uri)
  75. ret = sendPacket(eth_uri)
  76. // eth, _ := strconv.ParseFloat(fmt.Sprintf("%f", ret.Data[0].Quote.USD.Price), 64)
  77. eth := float64(ret.Data[0].Quote.USD.Price)
  78. return eth, mf1, mr
  79. }