Last active
June 6, 2017 19:54
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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