在 Conky 面板上顯示 Python 腳本輸出中,我建議在 Conky 面板上執行 Python 腳本以顯示美元和巴西雷亞爾的比特幣匯率。然而,由於這樣一個基本任務的記憶體消耗高於預期,我用 Go 重寫了腳本。現在,已編譯的二進位檔案可以處理該任務。這種方法非常適合 Go 初學者,提供了學習 API 處理和貨幣值文字格式設定的機會。詳細介紹如下:
完整程式碼在本文最後。
1 - 打包和導入
package main import ( "encoding/json" "fmt" "io" "net/http" "strconv" "github.com/dustin/go-humanize" )
- package main:將其標記為程式的入口點。
-
導入庫:
- coding/json:用於解析來自 API 的 JSON 回應。
- fmt:用於文字格式化和列印。
- io:用於讀取響應主體。
- net/http:用於發出 HTTP 請求。
- strconv:用於將字串轉換為數字。
- humanize:用於為數字添加千位分隔符號。透過 go get github.com/dustin/go- humanize 安裝。
2 - 全域常數
const ( apiURL = "https://economia.awesomeapi.com.br/json/last/BTC-USD,BTC-BRL" )
- apiURL:取得比特幣匯率的 API 端點。
3 - JSON 解析的結構
type CurrencyData struct { High string `json:"high"` Low string `json:"low"` } type APIResponse struct { BTCUSD CurrencyData `json:"BTCUSD"` BTCBRL CurrencyData `json:"BTCBRL"` }
- 貨幣資料:保存貨幣的高值和低值。
- APIResponse:表示具有 BTCUSD 和 BTCBRL 金鑰的完整 API 回應。
JSON 標籤 (json:"high") 將結構欄位對應到 JSON 鍵。
4 - 格式化貨幣值的函數
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 }
- 使用 strconv.ParseFloat 將值(字串)轉換為浮點數。
- 使用千位分隔符號和兩位小數格式化數字,並加上前綴(例如 $ 或 R$)。
5 - 主要功能
5.1 API請求
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 }
- http.Get(apiURL):向 API 發送 GET 請求。
- defer resp.Body.Close():確保回應正文在處理後關閉。
- io.ReadAll:讀取回應正文。
5.2 JSON解析
var data APIResponse if err := json.Unmarshal(body, &data); err != nil { writeError(err) return }
- json.Unmarshal:將 JSON 回應解析為 APIResponse 結構。
5.3 數據格式化
usdAlta := formatCurrency(data.BTCUSD.High, "$$") usdBaixa := formatCurrency(data.BTCUSD.Low, "$$") brlAlta := formatCurrency(data.BTCBRL.High, "R$$") brlBaixa := formatCurrency(data.BTCBRL.Low, "R$$")
格式化 API 提供的值以供顯示。
5.4 結果構建
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)
使用格式化值建立最終輸出字串。
6 - 錯誤記錄功能
func writeError(err error) { errMsg := fmt.Sprintf("Error: %v", err) fmt.Println(errMsg) }
將錯誤記錄到終端。
? btc_data.go
運行: go build btc_data.go && ./btc_data.go
package main import ( "encoding/json" "fmt" "io" "net/http" "strconv" "github.com/dustin/go-humanize" )
如果這篇文章對您有幫助或您喜歡它,請考慮貢獻:
以上是使用 Go 顯示比特幣匯率的詳細內容。更多資訊請關注PHP中文網其他相關文章!

在Go中,init函數用於包初始化。 1)init函數在包初始化時自動調用,適用於初始化全局變量、設置連接和加載配置文件。 2)可以有多個init函數,按文件順序執行。 3)使用時需考慮執行順序、測試難度和性能影響。 4)建議減少副作用、使用依賴注入和延遲初始化以優化init函數的使用。

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,執行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,確保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,確保Allimizegoroutines,確保AllizeNizeGoROutines,確保AllimizeGoroutines

goisbeneformervicesduetoitssimplicity,效率,androbustConcurrencySupport.1)go'sdesignemphasemphasizessimplicity and效率,Idealformicroservices.2))其ConcconcurnCurnInesSandChannelsOdinesSallessallessallessAlloSalosalOsalOsalOsalOndlingConconcConccompi.3)

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang在並發性上優於C ,而C 在原始速度上優於Golang。 1)Golang通過goroutine和channel實現高效並發,適合處理大量並發任務。 2)C 通過編譯器優化和標準庫,提供接近硬件的高性能,適合需要極致優化的應用。

選擇Golang的原因包括:1)高並發性能,2)靜態類型系統,3)垃圾回收機制,4)豐富的標準庫和生態系統,這些特性使其成為開發高效、可靠軟件的理想選擇。

Golang適合快速開發和並發場景,C 適用於需要極致性能和低級控制的場景。 1)Golang通過垃圾回收和並發機制提升性能,適合高並發Web服務開發。 2)C 通過手動內存管理和編譯器優化達到極致性能,適用於嵌入式系統開發。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

Dreamweaver Mac版
視覺化網頁開發工具

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。