僅需簡單 5 步,給你的 Golang 程式添加 GUI (使用 Electron )

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。建立一個 Golang app 是一件簡單又輕鬆的事情,但是有時候你想給你的應用錦上添花:建立一個 GUI!在本篇文章中,我將通過使用 astilectron 工具中的 bootstrap 以及 bundler 給一個簡單的 Golang 程式添加 GUI。我們的帶有 GUI 的 Golang app 能夠開啟一個檔案夾並且展示其中的內容。你可以在這裡找到完成後的 [代碼](https://github.com/asticode/go-astilectron-demo) :![](https://raw.githubusercontent.com/studygolang/gctt-images/master/go-gui-electron/0.png)## 第一步:組織項目結構檔案夾結構如下:```|--+ resources |--+ app |--+ static |--+ css |--+ base.css |--+ js |--+ index.js |--+ lib |--+ ... (all the css/js libs we need) |--+ index.html |--+ icon.icns |--+ icon.ico |--+ icon.png|--+ bundler.json|--+ main.go|--+ message.go```你將看到,我們需要 3 種不同格式的表徵圖以完成不同平台的編譯:`.icns` 用於 `darwin` 平台、`.ico` 用於 `windows` 平台、`.png` 用於 `linux` 平台。我們將使用以下 CSS/JS 庫:- [ astiloader ](https://github.com/asticode/js-toolbox)- [astimodaler](https://github.com/asticode/js-toolbox)- [astinotifier](https://github.com/asticode/js-toolbox)- [chartjs](http://www.chartjs.org/)- [fontAwesome](http://fontawesome.io/)## 第二步:搭建基礎架構### Go首先我們需要在 `main.go` 中匯入 [astilectron](https://github.com/asticode/go-astilectron) 的 bootstrap 源碼包 :```gopackage mainimport ("flag""github.com/asticode/go-astilectron""github.com/asticode/go-astilectron-bootstrap""github.com/asticode/go-astilog""github.com/pkg/errors")// Varsvar (AppName stringBuiltAt stringdebug = flag.Bool("d", false, "enables the debug mode")w *astilectron.Window)func main() {// Initflag.Parse()astilog.FlagInit()// Run bootstrapastilog.Debugf("Running app built at %s", BuiltAt)if err := bootstrap.Run(bootstrap.Options{AstilectronOptions: astilectron.Options{AppName: AppName,AppIconDarwinPath: "resources/icon.icns",AppIconDefaultPath: "resources/icon.png",},Debug: *debug,Homepage: "index.html",MenuOptions: []*astilectron.MenuItemOptions{{Label: astilectron.PtrStr("File"),SubMenu: []*astilectron.MenuItemOptions{{Label: astilectron.PtrStr("About")},{Role: astilectron.MenuItemRoleClose},},}},OnWait: func(_ *astilectron.Astilectron, iw *astilectron.Window, _ *astilectron.Menu, _ *astilectron.Tray, _ *astilectron.Menu) error {w = iwreturn nil},WindowOptions: &astilectron.WindowOptions{BackgroundColor: astilectron.PtrStr("#333"),Center: astilectron.PtrBool(true),Height: astilectron.PtrInt(700),Width: astilectron.PtrInt(700),},}); err != nil {astilog.Fatal(errors.Wrap(err, "running bootstrap failed"))}}```2 個全域變數 `AppName` 和 `BuiltAt` 將會通過 [bundler](https://github.com/asticode/go-astilectron-bundler) 打包自動添加進去。隨後我們將發現我們的首頁變成了 `index.html` ,我們將有一個含有 2 個項目( `about` 和 `close` )的菜單並且會出現一個 `700x700` , `中心對齊的` , `#333` 背景色的視窗。我們要在 go 上添加 `debug` 選項,因為我們需要使用 HTML/JS/CSS 調試工具。最後我們將指向 `astilectron.Window` 的指標存入全域變數 `w`,以備後續在使用 `OnWait` 選項時,它包含一個在視窗、菜單及其他所有對象被建立時立即執行的回呼函數。### HTML現在我們需要在 `resources/app/index.html` 中建立我們的 HTML 首頁:```html<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <link rel="stylesheet" href="static/css/base.css"/> <link rel="stylesheet" href="static/lib/astiloader/astiloader.css"> <link rel="stylesheet" href="static/lib/astimodaler/astimodaler.css"> <link rel="stylesheet" href="static/lib/astinotifier/astinotifier.css"> <link rel="stylesheet" href="static/lib/font-awesome-4.7.0/css/font-awesome.min.css"></head><body> <div class="left" id="dirs"></div> <div class="right"> <div class="title"><span id="path"></span></div> <div class="panel"><span class="stat" id="files_count"></span> file(s)</div> <div class="panel"><span class="stat" id="files_size"></span> of file(s)</div> <div class="panel" id="files_panel"> <div class="chart_title">Files repartition</div> <div id="files"></div> </div> </div> <script src="static/js/index.js"></script> <script src="static/lib/astiloader/astiloader.js"></script> <script src="static/lib/astimodaler/astimodaler.js"></script> <script src="static/lib/astinotifier/astinotifier.js"></script> <script src="static/lib/chart/chart.min.js"></script> <script type="text/javascript"> index.init(); </script></body></html>```這裡沒什麼特殊的地方,我們聲明我們的 `css` 和 `js` 檔案,我們設定 html 檔案結構並且需要確保我們的 `js` 指令碼通過 `index.init()` 進行了初始化### CSS現在需要在 `resources/app/static/css/base.css` 檔案中建立我們的 CSS:```css* { box-sizing: border-box;}html, body { background-color: #fff; color: #333; height: 100%; margin: 0; width: 100%;}.left { background-color: #333; color: #fff; float: left; height: 100%; overflow: auto; padding: 15px; width: 40%;}.dir { cursor: pointer; padding: 3px;}.dir .fa { margin-right: 5px;}.right { float: right; height: 100%; overflow: auto; padding: 15px; width: 60%;}.title { font-size: 1.5em; text-align: center; word-wrap: break-word;}.panel { background-color: #f1f1f1; border: solid 1px #e1e1e1; border-radius: 4px; margin-top: 15px; padding: 15px; text-align: center;}.stat { font-weight: bold;}.chart_title { margin-bottom: 5px;}```### JS然後我們在 `resources/app/static/js/index.js` 中建立 JS :```javascriptlet index = { init: function() { // Init asticode.loader.init(); asticode.modaler.init(); asticode.notifier.init(); }};```通過 `init` 方法正確的將庫初始化。## 第三步:建立起 Go 與 Javascript 間的通訊萬事俱備,只欠東風:我們需要將 Go 與 Javascript 建立起通訊。### Javascript 通訊 Go為了讓 Javascript 與 Go 進行通訊,首先從 Javascript 向 Go 發送一條訊息,並且在 GO 接受到訊息後執行回呼函數:```javascript// This will wait for the astilectron namespace to be readydocument.addEventListener('astilectron-ready', function() { // This will send a message to Go astilectron.sendMessage({name: "event.name", payload: "hello"}, function(message) { console.log("received " + message.payload) });})```同時我們在 Go 中監聽來自 Javascript 的訊息,並且通過 bootstrap 的 `MessageHandler` 給 Javascript 發送訊息:```gofunc main() {bootstrap.Run(bootstrap.Options{MessageHandler: handleMessages,})}// handleMessages handles messagesfunc handleMessages(_ *astilectron.Window, m bootstrap.MessageIn) (payload interface{}, err error) {switch m.Name {case "event.name":// Unmarshal payloadvar s stringif err = json.Unmarshal(m.Payload, &path); err != nil { payload = err.Error() return}payload = s + " world"}return}```這是一個簡單的例子,將在 js 的輸出中列印出 `received hello world` 。在這種情形中,我們需要更多的邏輯因為我們想要允許開啟一個檔案夾並且展示其中的內容。因此我們將下面的代碼加入到 `resources/app/static/js/index.js` 中:```javascriptlet index = { addFolder(name, path) { let div = document.createElement("div"); div.className = "dir"; div.onclick = function() { index.explore(path) }; div.innerHTML = `<i class="fa fa-folder"></i><span>` + name + `</span>`; document.getElementById("dirs").appendChild(div) }, init: function() { // Wait for astilectron to be ready document.addEventListener('astilectron-ready', function() { // Explore default path index.explore(); }) }, explore: function(path) { // Create message let message = {"name": "explore"}; if (typeof path !== "undefined") { message.payload = path } // Send message asticode.loader.show(); astilectron.sendMessage(message, function(message) { // Init asticode.loader.hide(); // Check error if (message.name === "error") { asticode.notifier.error(message.payload); return } // Process path document.getElementById("path").innerHTML = message.payload.path; // Process dirs document.getElementById("dirs").innerHTML = "" for (let i = 0; i < message.payload.dirs.length; i++) { index.addFolder(message.payload.dirs[i].name, message.payload.dirs[i].path); } // Process files document.getElementById("files_count").innerHTML = message.payload.files_count; document.getElementById("files_size").innerHTML = message.payload.files_size; document.getElementById("files").innerHTML = ""; if (typeof message.payload.files !== "undefined") { document.getElementById("files_panel").style.display = "block"; let canvas = document.createElement("canvas"); document.getElementById("files").append(canvas); new Chart(canvas, message.payload.files); } else { document.getElementById("files_panel").style.display = "none"; } }) }};```一旦 Javascript 的 `astilectron` 命名空間準備好,它執行新的 `explore` 方法,該方法會給 Go 發送一條訊息,接收返回的資訊,並且更新相應的 HTML 。然後我們將下面代碼加入到 `message.go` 中:```gopackage mainimport ("encoding/json""io/ioutil""os""os/user""path/filepath""sort""strconv""github.com/asticode/go-astichartjs""github.com/asticode/go-astilectron""github.com/asticode/go-astilectron-bootstrap")// handleMessages handles messagesfunc handleMessages(_ *astilectron.Window, m bootstrap.MessageIn) (payload interface{}, err error) {switch m.Name {case "explore":// Unmarshal payloadvar path stringif len(m.Payload) > 0 {// Unmarshal payloadif err = json.Unmarshal(m.Payload, &path); err != nil {payload = err.Error()return}}// Exploreif payload, err = explore(path); err != nil {payload = err.Error()return}}return}// Exploration represents the results of an explorationtype Exploration struct {Dirs []Dir `json:"dirs"`Files *astichartjs.Chart `json:"files,omitempty"`FilesCount int `json:"files_count"`FilesSize string `json:"files_size"`Path string `json:"path"`}// PayloadDir represents a dir payloadtype Dir struct {Name string `json:"name"`Path string `json:"path"`}// explore explores a path.// If path is empty, it explores the user's home directoryfunc explore(path string) (e Exploration, err error) {// If no path is provided, use the user's home dirif len(path) == 0 {var u *user.Userif u, err = user.Current(); err != nil {return}path = u.HomeDir}// Read dirvar files []os.FileInfoif files, err = ioutil.ReadDir(path); err != nil {return}// Init exploratione = Exploration{Dirs: []Dir{},Path: path,}// Add previous dirif filepath.Dir(path) != path {e.Dirs = append(e.Dirs, Dir{Name: "..",Path: filepath.Dir(path),})}// Loop through filesvar sizes []intvar sizesMap = make(map[int][]string)var filesSize int64for _, f := range files {if f.IsDir() {e.Dirs = append(e.Dirs, Dir{Name: f.Name(),Path: filepath.Join(path, f.Name()),})} else {var s = int(f.Size())sizes = append(sizes, s)sizesMap[s] = append(sizesMap[s], f.Name())e.FilesCount++filesSize += f.Size()}}// Prepare files sizeif filesSize < 1e3 {e.FilesSize = strconv.Itoa(int(filesSize)) + "b"} else if filesSize < 1e6 {e.FilesSize = strconv.FormatFloat(float64(filesSize)/float64(1024), 'f', 0, 64) + "kb"} else if filesSize < 1e9 {e.FilesSize = strconv.FormatFloat(float64(filesSize)/float64(1024*1024), 'f', 0, 64) + "Mb"} else {e.FilesSize = strconv.FormatFloat(float64(filesSize)/float64(1024*1024*1024), 'f', 0, 64) + "Gb"}// Prepare files chartsort.Ints(sizes)if len(sizes) > 0 {e.Files = &astichartjs.Chart{Data: &astichartjs.Data{Datasets: []astichartjs.Dataset{{BackgroundColor: []string{astichartjs.ChartBackgroundColorYellow,astichartjs.ChartBackgroundColorGreen,astichartjs.ChartBackgroundColorRed,astichartjs.ChartBackgroundColorBlue,astichartjs.ChartBackgroundColorPurple,},BorderColor: []string{astichartjs.ChartBorderColorYellow,astichartjs.ChartBorderColorGreen,astichartjs.ChartBorderColorRed,astichartjs.ChartBorderColorBlue,astichartjs.ChartBorderColorPurple,},}}},Type: astichartjs.ChartTypePie,}var sizeOther intfor i := len(sizes) - 1; i >= 0; i-- {for _, l := range sizesMap[sizes[i]] {if len(e.Files.Data.Labels) < 4 {e.Files.Data.Datasets[0].Data = append(e.Files.Data.Datasets[0].Data, sizes[i])e.Files.Data.Labels = append(e.Files.Data.Labels, l)} else {sizeOther += sizes[i]}}}if sizeOther > 0 {e.Files.Data.Datasets[0].Data = append(e.Files.Data.Datasets[0].Data, sizeOther)e.Files.Data.Labels = append(e.Files.Data.Labels, "other")}}return}```在接收到正確的資訊時,它將執行新的 `explore` 方法,並返回關於目錄的有價值的資訊。### 建立從 Go 向 Javascript 通訊為了建立從 Go 向 Javascript 的通訊,我們首先需要從 Go 中向 Javascript 發送一條訊息並且在 Javascript 收到訊息後執行回調。```go// This will send a message and execute a callback// Callbacks are optionalbootstrap.SendMessage(w, "event.name", "hello", func(m *bootstrap.MessageIn) { // Unmarshal payload var s string json.Unmarshal(m.Payload, &s) // Process message log.Infof("received %s", s)})```同時我們在 Javascript 中監聽來自 Go 的訊息並發送一個選項訊息給 Go:```javascript// This will wait for the astilectron namespace to be readydocument.addEventListener('astilectron-ready', function() { // This will listen to messages sent by GO astilectron.onMessage(function(message) { // Process message if (message.name === "event.name") { return {payload: message.message + " world"}; } });})```這個簡單的例子將在 Go 的輸出中列印 `received hello world` 。在我們的項目裡,我們先將下面的代碼加入到 `main.go` 中:```gofunc main() {bootstrap.Run(bootstrap.Options{MenuOptions: []*astilectron.MenuItemOptions{{Label: astilectron.PtrStr("File"),SubMenu: []*astilectron.MenuItemOptions{{Label: astilectron.PtrStr("About"),OnClick: func(e astilectron.Event) (deleteListener bool) {if err := bootstrap.SendMessage(w, "about", htmlAbout, func(m *bootstrap.MessageIn) {// Unmarshal payloadvar s stringif err := json.Unmarshal(m.Payload, &s); err != nil {astilog.Error(errors.Wrap(err, "unmarshaling payload failed"))return}astilog.Infof("About modal has been displayed and payload is %s!", s)}); err != nil {astilog.Error(errors.Wrap(err, "sending about event failed"))}return},},{Role: astilectron.MenuItemRoleClose},},}},OnWait: func(_ *astilectron.Astilectron, iw *astilectron.Window, _ *astilectron.Menu, _ *astilectron.Tray, _ *astilectron.Menu) error {w = iwgo func() {time.Sleep(5 * time.Second)if err := bootstrap.SendMessage(w, "check.out.menu", "Don't forget to check out the menu!"); err != nil {astilog.Error(errors.Wrap(err, "sending check.out.menu event failed"))}}()return nil},})}```它使得 關於 選項變成可點擊的,並且渲染出一個有合適內容的模態框,在 Go app 完成初始化 5s 後它會顯示一個提示框。最後我們將下面的代碼加入到 `resources/app/static/js/index.js` 中:```javascriptlet index = { about: function(html) { let c = document.createElement("div"); c.innerHTML = html; asticode.modaler.setContent(c); asticode.modaler.show(); }, init: function() { // Wait for astilectron to be ready document.addEventListener('astilectron-ready', function() { // Listen index.listen(); }) }, listen: function() { astilectron.onMessage(function(message) { switch (message.name) { case "about": index.about(message.payload); return {payload: "payload"}; break; case "check.out.menu": asticode.notifier.info(message.payload); break; } }); }};```它將監聽 Go 發送過來的訊息並做出相應的反應。## 第四步: 打包到 app現在代碼已經完成,我們需要確保我們能夠以最好的方式把 Golang GUI app 呈現給我們的使用者: - 一個 MacOSX app 給 `darwin` 使用者 - 一個含有好看表徵圖的 `.exe` 給 `windows` 使用者 - 一個簡單的源碼檔案給 `linux` 使用者幸運的是,我們可以通過 astilectron 的 bundler 來進行操作。首先我們通過下面命令進行安裝:```$ go get -u github.com/asticode/go-astilectron-bundler/...```然後我們在 `main.go` 中給 bootstrap 添加配置項:```gofunc main() {bootstrap.Run(bootstrap.Options{Asset: Asset,RestoreAssets: RestoreAssets,})}```然後我們建立設定檔,命名為 `bundler.json` :```json{ "app_name": "Astilectron demo", "icon_path_darwin": "resources/icon.icns", "icon_path_linux": "resources/icon.png", "icon_path_windows": "resources/icon.ico", "output_path": "output"}```最後我們在專案檔夾下運行下面的命令(確保 `$GOPATH/bin` 在你的 `$PATH` 中)```$ astilectron-bundler -v```## 第五步: 實際效果啊哈!結果在 `output/<os>-<arch>` 檔案夾下,快來去試一試 :)![](https://raw.githubusercontent.com/studygolang/gctt-images/master/go-gui-electron/0.png)你當然可以打包你的 Golang GUI app 給其他環境,在 bundler 打包文檔中查看如何將程式打包到其他環境。## 結論感謝 astilectron 的 bootstrap 和 bundler ,有了一點點的組織和結構,給你的 Golang 程式添加 GUI 從未如此簡單。需要指出的是這種方法有 2 個主要的缺點:- 程式碼封裝的大小至少有 50 MB,第一次執行後,檔案大小至少將有 200 MB- 記憶體的消耗有些瘋狂,因為 Electron 並不擅長對記憶體的管理但是如果你準備掌握它,那麼你在給你的程式添加 GUI 時將非常便利!享受 GUI 編碼的快樂吧!

via: https://medium.com/@social_57971/how-to-add-a-gui-to-your-golang-app-in-5-easy-steps-c25c99d4d8e0

作者:Asticode 譯者:fengchunsgit 校對:rxcai polaris1119

本文由 GCTT 原創編譯,Go語言中文網 榮譽推出

本文由 GCTT 原創翻譯,Go語言中文網 首發。也想加入譯者行列,為開源做一些自己的貢獻嗎?歡迎加入 GCTT!
翻譯工作和譯文發表僅用於學習和交流目的,翻譯工作遵照 CC-BY-NC-SA 協議規定,如果我們的工作有侵犯到您的權益,請及時聯絡我們。

歡迎遵照 CC-BY-NC-SA 協議規定 轉載,敬請在本文中標註並保留原文/譯文連結和作者/譯者等資訊。
文章僅代表作者的知識和看法,如有不同觀點,請樓下排隊吐槽

8107 次點擊  ∙  5 贊  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.