-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
66 lines (53 loc) · 1.29 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"time"
"golang.org/x/text/language"
"golang.org/x/text/message"
)
const binanceURL = "https://api.binance.com/api/v3"
const timeout = 20 // timeout in seconds
const pricePlaceholder = "---"
type PriceTicker struct {
Symbol string `json:"symbol"`
Price string `json:"price"`
}
func main() {
client := &http.Client{}
printer := message.NewPrinter(language.English)
ctx, cancel := context.WithTimeout(context.Background(), timeout*time.Second)
defer cancel()
if len(os.Args) != 2 {
fmt.Println("USAGE: coinprice [SYMBOL]\nEXAMPLE:\n\tcoinprice BTCUSDT")
os.Exit(1)
}
symbol := os.Args[1]
url := fmt.Sprintf("%s/ticker/price?symbol=%s", binanceURL, symbol)
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
printPlaceholderAndExit()
}
resp, err := client.Do(req)
if err != nil {
printPlaceholderAndExit()
}
defer resp.Body.Close()
var ticker PriceTicker
if err = json.NewDecoder(resp.Body).Decode(&ticker); err != nil {
printPlaceholderAndExit()
}
symbolPrice, err := strconv.ParseFloat(ticker.Price, 32)
if err != nil {
printPlaceholderAndExit()
}
printer.Printf("%.2f", symbolPrice)
}
func printPlaceholderAndExit() {
fmt.Print(pricePlaceholder)
os.Exit(1)
}