使用Golang編寫一個在Mac通知欄上顯示ETH價格的小工具

一、前言

作爲一個剛接觸Go語言的初學者,總得寫點代碼練習一下。考慮到自身需求,就寫了個這麼一個小工具。記錄在這裏和大家一起分享,給有需求的同志提供一點參考。

這個工具很簡單,用網上現成的庫,並將附帶的示例稍微修改下就可以了。

二、準備工作

  1. 打開https://github.com/getlantern/systray並git clone,我們工作就是在它給出的example中進行修改。
  2. 網上下載一張以太坊的Logo(PNG格式的)
  3. 安裝最新版本go(1.13以上)並設置GOPATH,這個可以去官網看教程
  4. 設置GOPROXY="https://goproxy.io"。建議在.bash_profile裏設置。

三、創建工程

打開終端,建立工程目錄並使用go module。如下示例:

➜  ~ cd work/
➜  work mkdir ethprice
➜  work cd ethprice/
➜  ethprice go mod init ethprice
go: creating new go.mod: module ethprice
➜  ethprice 

注意這裏的work不要在GOPATH目錄下。使用vscode打開剛纔的ethprice文件夾,在根目錄下建立main.go文件和icon文件夾,並將以太坊logo改名爲logo.png放入icon文件夾下。將如下圖:
在這裏插入圖片描述

四、處理logo

將前面下載的systray中example\icon\make_icon.sh也copy到icon目錄下。在vscode裏打開終端,切換到該目錄並運行sh ./make_icon.sh logo.png,它會在當前目錄下生成一個iconunix.go的文件,這就是我們小工具所需要的logo。下面是make_icon.sh裏的代碼:

#/bin/sh

if [ -z "$GOPATH" ]; then
    echo GOPATH environment variable not set
    exit
fi

if [ ! -e "$GOPATH/bin/2goarray" ]; then
    echo "Installing 2goarray..."
    go get github.com/cratonica/2goarray
    if [ $? -ne 0 ]; then
        echo Failure executing go get github.com/cratonica/2goarray
        exit
    fi
fi

if [ -z "$1" ]; then
    echo Please specify a PNG file
    exit
fi

if [ ! -f "$1" ]; then
    echo $1 is not a valid file
    exit
fi    

OUTPUT=iconunix.go
echo Generating $OUTPUT
echo "//+build linux darwin" > $OUTPUT
echo >> $OUTPUT
cat "$1" | $GOPATH/bin/2goarray Data icon >> $OUTPUT
if [ $? -ne 0 ]; then
    echo Failure generating $OUTPUT
    exit
fi
echo Finished

可以看到,它安裝了一個2goarray庫並且將轉換後的數據輸出到iconunix.go中,變量名爲Data,包名爲icon。這裏也可以自己修改爲不同的名字。

五、編寫主程序

參照systray中的示例,我們在main.go中寫入如下代碼:

package main

import (
	"encoding/json"
	"ethprice/icon"
	"fmt"
	"net/http"
	"time"

	"github.com/getlantern/systray"
)

const URL = "https://api.pro.coinbase.com/products/ETH-USD/ticker"

type EthPrice struct {
	Price string `json:price`
}
type Callback func(s string)

var priceInfo = new(EthPrice)
var t *time.Ticker

var step = 15

func backgroundTask(cb Callback) {
	t = time.NewTicker(time.Duration(step) * time.Second)
	for range t.C {
		cb(fetchPrice())
	}
}

func fetchPrice() string {
	resp, err := http.Get(URL)
	if err != nil {
		return "-"
	}
	defer resp.Body.Close()
	json.NewDecoder(resp.Body).Decode(priceInfo)
	return fmt.Sprintf("ETH $%s(每%d秒)", priceInfo.Price, step)
}

func main() {
	systray.Run(onReady, onExit)
}

func onReady() {
	go backgroundTask(systray.SetTitle)
	systray.SetIcon(icon.Data)
	systray.SetTitle(fmt.Sprintf("ETH $%s(每%d秒)", priceInfo.Price, step))
	systray.SetTooltip("定時刷新ETH價格")
	oneMinite := systray.AddMenuItem("每分鐘", "每分鐘刷新一次")
	halfMinite := systray.AddMenuItem("每半分鐘", "每30秒刷新一次")
	quartor := systray.AddMenuItem("每15秒", "每15秒刷新一次")
	mQuit := systray.AddMenuItem("退出", "退出程序")
	systray.SetTitle(fetchPrice())

	go func() {
		for {
			select {
			case <-mQuit.ClickedCh:
				systray.Quit()
				return
			case <-oneMinite.ClickedCh:
				if step != 60 {
					step = 60
					systray.SetTitle(fmt.Sprintf("ETH $%s(每%d秒)", priceInfo.Price, step))
					t = time.NewTicker(time.Duration(step) * time.Second)
				}

			case <-halfMinite.ClickedCh:
				if step != 30 {
					step = 30
					systray.SetTitle(fmt.Sprintf("ETH $%s(每%d秒)", priceInfo.Price, step))
					t = time.NewTicker(time.Duration(step) * time.Second)
				}

			case <-quartor.ClickedCh:
				if step != 15 {
					step = 15
					systray.SetTitle(fmt.Sprintf("ETH $%s(每%d秒)", priceInfo.Price, step))
					t = time.NewTicker(time.Duration(step) * time.Second)
				}
			}
		}
	}()

}

// clean up here
func onExit() {
	t.Stop()
}

這裏icon包位於本地包(目錄)ethprice之下,本地包就是go mod init時定義的包。由於是初學者,代碼寫的不完善,還有一些需要優化的地方,見諒。

六、編譯運行

切換到項目根目錄並運行go build,會在根目錄下生成ethprice可執行文件。讓我們後臺運行它:

./ethprice &

這裏就可以在屏幕通知欄看到ETH價格了,點擊它還可以改變查詢間隔和退出程序。
在這裏插入圖片描述

七、設置開機自動運行

我們把它設置成開機自動運行,先點擊程序選擇退出,然後再把它copy到用戶根目錄:

cp ethprice ~

接着我們在vscode外部打開一個終端,鍵入vim auto.sh,內容如下:

#!/bin/sh
./ethprice &

escape,再按":"進入底部命令模式,輸入wq回車保存。注意,接下來這一步相當重要,就是chmod 777 auto.sh

設置開機啓動,先參照https://jingyan.baidu.com/article/77b8dc7fbc943c6175eab64e.html ,在登錄項這一步,點擊左下角+號,將auto.sh添加進去並選中隱藏。如下圖:
在這裏插入圖片描述

這裏需要事先設定使用終端打開.sh文件。打開Finder,右鍵點擊auto.sh,選擇打開方式,此時如果第一項爲xcode的話需要改過來。選擇其它,在啓用那裏選所有程序,搜索裏鍵入終端,然後點擊左邊列表裏的終端。如下圖:
在這裏插入圖片描述
點擊打開,並不會有輸出。此時再右鍵點擊auto.sh,打開方式第一項已經變成終端了。

八、註銷重登錄

註銷當前用戶,再重新登錄,我們就可以在通知欄看到ETH價格啦!Over!

這裏其實可以再擴展一下,比如把點擊彈出來的菜單不弄成設定查詢間隔,而是查詢BTC\EOS等。有興趣和需求的同志自己動手了!

歡迎大家留言指出錯誤或者提出改進意見。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章