« Previous 1 2 3 Next »
Program GUIs in Go with Fyne
Fyne Work
Themes
The SetTheme()
method in line 16 gives the program window different looks. Fyne brings two built-in themes for a light appearance (LightTheme
) and a dark color scheme (DarkTheme
). By default, a GUI created with Fyne appears in the dark theme (Figure 2).
Because the GUI remains in a continuous loop, you can toggle between the light (line 20) and dark (line 24) themes on the fly. An item under the sample application's View menu has instructions for changing the theme.
Graphical Dialogs
Fyne comes with several dialogs (e.g., for file selection or user information). For example, line 38 calls a file selection dialog with dialog.ShowFileOpen()
(Figure 3). This function takes a callback function as its first parameter. The second parameter specifies the Fyne window in which the dialog should appear.
The program passes to the callback function an interface, URIReadCloser
, that describes the selected file's data stream. In line 46, read.URI().String()
then reads the selected file. Finally, you need to use TrimPrefix()
to remove the leading file://
from the file path string variable so that the program can process the result downstream as the source file for which you are calculating a checksum.
Outsourced Function
The genChecksum()
function (Listing 3), which calculates checksums, resides in a separate file named genchecksum.go
. This arrangement allows the function to be started in a Go routine – a kind of separate thread – to decouple the checksum calculation from the GUI. Otherwise, the calculation would freeze the GUI and it would be unusable for the duration of the calculation.
Listing 3
genchecksum.go
01 package main 02 03 import ( 04 "crypto/md5" 05 "crypto/sha1" 06 "crypto/sha256" 07 "crypto/sha512" 08 "encoding/hex" 09 "hash" 10 "io" 11 "log" 12 "os" 13 ) 14 15 func genChecksum(file, hashfunc string) string { 16 var h hash.Hash 17 18 f, err := os.Open(file) 19 if err != nil { 20 log.Fatal(err) 21 } 22 23 defer f.Close() 24 25 switch hashfunc { 26 case "md5": 27 h = md5.New() 28 case "sha1": 29 h = sha1.New() 30 case "sha256": 31 h = sha256.New() 32 case "sha512": 33 h = sha512.New() 34 } 35 36 if _, err := io.Copy(h, f); err != nil { 37 log.Fatal(err) 38 } 39 40 result := hex.EncodeToString(h.Sum(nil)) 41 42 return result 43 }
The genChecksum()
function takes two parameters. The first is the path to the file whose checksum is to be calculated, and the second is the hash function to be applied. The required algorithms for different hash functions are provided by the standard Go library in the crypto
package.
« Previous 1 2 3 Next »
Buy this article as PDF
(incl. VAT)
Buy ADMIN Magazine
Subscribe to our ADMIN Newsletters
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Most Popular
Support Our Work
ADMIN content is made possible with support from readers like you. Please consider contributing when you've found an article to be beneficial.