Last active
December 28, 2015 05:39
-
-
Save dbrgn/7451806 to your computer and use it in GitHub Desktop.
Fetch current bitcoin prices with Go.
This file contains hidden or 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 ( | |
"fmt" | |
"net/http" | |
"io/ioutil" | |
"encoding/json" | |
) | |
const baseUrl = "http://data.mtgox.com/api/2/%s/money/ticker" | |
// Available currencies | |
type Currency struct { | |
Name string | |
Symbol string | |
} | |
var currencies = []Currency{ | |
{"BTCUSD", "$"}, | |
{"BTCEUR", "€"}, | |
} | |
// API response types | |
type ApiResponse struct { | |
Result string | |
Data DataItem | |
} | |
type DataItem struct { | |
High CurrencyInfo | |
Low CurrencyInfo | |
Avg CurrencyInfo | |
Last CurrencyInfo | |
} | |
type CurrencyInfo struct { | |
Value float32 `json:",string"` | |
Display string | |
Currency string | |
} | |
// Function to query API | |
func getMtgoxJson (url string) []byte { | |
// Build HTTP request | |
client := &http.Client{} | |
req, err := http.NewRequest("GET", url, nil) | |
if err != nil { | |
panic(fmt.Sprintf("%v", err)) | |
} | |
req.Header.Add("Accept", "application/json") | |
// Send request | |
resp, err := client.Do(req) | |
if err != nil { | |
panic(fmt.Sprintf("%v", err)) | |
} | |
// Close response body when function returns | |
defer resp.Body.Close() | |
// Read body | |
body, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
panic(fmt.Sprintf("%v", err)) | |
} | |
return body | |
} | |
// Function to parse JSON | |
func parseJson (data []byte) ApiResponse { | |
var resp ApiResponse | |
err := json.Unmarshal(data, &resp) | |
if err != nil { | |
panic("Could not decode JSON.") | |
} | |
if resp.Result != "success" { | |
panic(fmt.Sprintf("API query was not successful: %v", resp.Result)) | |
} | |
return resp | |
} | |
// Main function | |
func main() { | |
for _, currency := range currencies { | |
url := fmt.Sprintf(baseUrl, currency.Name) | |
rawData := getMtgoxJson(url) | |
data := parseJson(rawData) | |
fmt.Printf("1 BTC = %.2f %s\n", data.Data.Last.Value, currency.Symbol) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment