In Displaying Python Script Outputs on Conky Panels, I suggested running a Python script on a Conky panel to display Bitcoin exchange rates in USD and BRL. However, due to higher-than-expected memory consumption for such a basic task, I rewrote the script in Go. Now, a compiled binary handles the task. This approach is ideal for Go beginners, offering a chance to learn API handling and text formatting for monetary values. Here's a breakdown:
The complete code is at the end of this article.
package main import ( "encoding/json" "fmt" "io" "net/http" "strconv" "github.com/dustin/go-humanize" )
const ( apiURL = "https://economia.awesomeapi.com.br/json/last/BTC-USD,BTC-BRL" )
type CurrencyData struct { High string `json:"high"` Low string `json:"low"` } type APIResponse struct { BTCUSD CurrencyData `json:"BTCUSD"` BTCBRL CurrencyData `json:"BTCBRL"` }
JSON tags (json:"high") map struct fields to JSON keys.
func formatCurrency(value string, prefix string) string { floatValue, err := strconv.ParseFloat(value, 64) if err != nil { return "N/A" } formattedValue := fmt.Sprintf("%s%s", prefix, humanize.FormatFloat("#,###.##", floatValue)) return formattedValue }
resp, err := http.Get(apiURL) if err != nil { writeError(err) return } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { writeError(err) return }
var data APIResponse if err := json.Unmarshal(body, &data); err != nil { writeError(err) return }
usdAlta := formatCurrency(data.BTCUSD.High, "$$") usdBaixa := formatCurrency(data.BTCUSD.Low, "$$") brlAlta := formatCurrency(data.BTCBRL.High, "R$$") brlBaixa := formatCurrency(data.BTCBRL.Low, "R$$")
Formats the API-provided values for display.
formattedData := fmt.Sprintf( "\n\n${color white}BTC - USD\n${color}${color green} High: ${color}${color white}%s\n${color red} Low: ${color}${color white}%s\n\n"+ "${color white}BTC - BRL\n${color}${color green} High: ${color}${color white}%s\n${color red} Low: ${color}${color white}%s\n", usdAlta, usdBaixa, brlAlta, brlBaixa, ) fmt.Println(formattedData)
Creates the final output string with the formatted values.
func writeError(err error) { errMsg := fmt.Sprintf("Error: %v", err) fmt.Println(errMsg) }
Logs errors to the terminal.
Run: go build btc_data.go && ./btc_data.go
package main import ( "encoding/json" "fmt" "io" "net/http" "strconv" "github.com/dustin/go-humanize" )
If this article helped you or you enjoyed it, consider contributing:
The above is the detailed content of Displaying Bitcoin Exchange Rates with Go. For more information, please follow other related articles on the PHP Chinese website!