Skip to content

Instantly share code, notes, and snippets.

@AbeEstrada
Last active June 6, 2017 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AbeEstrada/4abf4c00cc7cac7837e1881e58d81d7e to your computer and use it in GitHub Desktop.
Save AbeEstrada/4abf4c00cc7cac7837e1881e58d81d7e to your computer and use it in GitHub Desktop.
coins, get the current price of BTC, ETH and LTC from the Coinbase API
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
)
type AmountResponse struct {
Amount string `json:amount`
Currency string `json:currency`
}
type DataResponse struct {
Data AmountResponse `json:data`
}
func price(coin string, ch chan<- string) {
client := &http.Client{}
url := fmt.Sprintf("https://api.coinbase.com/v2/prices/%s-USD/spot", coin)
req, reqErr := http.NewRequest("GET", url, nil)
if reqErr != nil {
log.Fatal(reqErr)
}
req.Header.Set("CB-VERSION", "2017-03-25")
res, resErr := client.Do(req)
if resErr != nil {
log.Fatal(resErr)
}
body, readErr := ioutil.ReadAll(res.Body)
res.Body.Close()
if readErr != nil {
log.Fatal(readErr)
}
data := DataResponse{}
jsonErr := json.Unmarshal(body, &data)
if jsonErr != nil {
log.Fatal(jsonErr)
}
ch <- fmt.Sprintf("%s $%s", coin, data.Data.Amount)
}
func main() {
fmt.Println(time.Now().Format("2006/01/02 15:04:05"))
ch := make(chan string)
coins := []string{"BTC", "ETH", "LTC"}
for _, coin := range coins {
go price(coin, ch)
}
for range coins {
fmt.Println(<-ch)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment