Quotes Generator

In this tutorial, we will be building on the default Vue/Webpack template to create a quotes generator. We shall cover how we can group methods into a struct in Go and how to use the Go runtime object.

It is assumed you have completed and understood the template tutorial. We will continue from where we left off.

Creating the Quotes Struct

Wails allows you to bind structs to your application. Methods that are exposed, ie those with their first letters capitalised, will be bound to the application.

We will start by creating a new file: quotes.go.

  1. package main
  2. // Quotes is our bound Quote Struct
  3. type Quotes struct {
  4. }
  5. // NewQuotes creates a new Quotes Struct
  6. func NewQuotes() *Quotes {
  7. return &Quotes{}
  8. }
  9. // GetQuote returns a quote
  10. func (q *Quotes) GetQuote() string {
  11. return "s/be/in - Mat Ryer"
  12. }

Our Quotes struct has one method GetQuote. When this is bound to the application, Wails will bind it to the frontend as backend.Quotes. Because GetQuote is an exposed method, it will be bound in the frontend as backend.Quotes.GetQuote.

The NewQuotes method is simply a convention for creating a new instance of a struct. Wails requires that structs are instantiated before binding, so we will use this function in the main app.

Binding it to the application

Now that we have our initial struct, let’s bind it to the app:

  1. package main
  2. import (
  3. "github.com/leaanthony/mewn"
  4. "github.com/wailsapp/wails"
  5. )
  6. func basic() string {
  7. return "Hello World!"
  8. }
  9. func main() {
  10. js := mewn.String("./frontend/dist/app.js")
  11. css := mewn.String("./frontend/dist/app.css")
  12. app := wails.CreateApp(&wails.AppConfig{
  13. Width: 1024,
  14. Height: 768,
  15. Title: "Quotes",
  16. JS: js,
  17. CSS: css,
  18. Colour: "#131313",
  19. })
  20. app.Bind(basic)
  21. app.Bind(NewQuotes()) // Add this
  22. app.Run()
  23. }

Binding our quotes struct is a single line change to our existing main function. We can test this in the front end by serving the project again:

  • Run wails serve in the project directory
  • When it is ready, run npm run serve in the frontend directory

When it is ready, open the browser to the project url and you should see the same familiar screen as in the template tutorial:

Quotes Generator - 图1

If you open up the browser’s inspector window and select console, you should be able to access the bound Quotes struct:

Quotes Generator - 图2

Note that the GetQuote() method is available to us. This, just like bound functions, returns a Javascript promise. We can run the method and print the output like so:

Quotes Generator - 图3

Now that we have access to our Quotes struct, let’s add more quotes.

Better Quotes

A quote traditionally has a text and an author. Currently we are returning a single string from our GetQuote method, but it would be better to return a struct. Let’s define it:

  1. // Quote holds a single quote and the author who said it
  2. type Quote struct {
  3. Text string `json:"text"`
  4. Author string `json:"author"`
  5. }

We can now update our GetQuote method to return a Quote:

  1. // GetQuote returns a quote
  2. func (q *Quotes) GetQuote() *Quote {
  3. return &Quote{Text: "s/be/in", Author: "Mat Ryer"}
  4. }

If the previous wails serve is still running, press ctrl-c to stop it and re-run the serve command. The frontend does not need recompiling and will automatically reconnect to the backend when it becomes available. During that connection time, you will see a screen like this letting you know it is trying to reconnect to the backend:

Quotes Generator - 图4

Once reconnected, open the console again and re-issue the GetQuote command. You should see something like the following:

Quotes Generator - 图5

Now that we have the data in a format we can manipulate, we can update our frontend code to use it.

Rendering the Quotes

Let’s create a new component for rendering the quotes. It will be based on our HelloWorld component, so make a copy of this file and name it Quote.vue.

The first thing we will do is register our new Quote component in App.vue:

  1. <template>
  2. <div id="app">
  3. <img alt="Wails logo" src="./assets/images/logo.png" class="logo zoomIn">
  4. <Quote />
  5. </div>
  6. </template>
  7. <script>
  8. import Quote from "./components/Quote.vue";
  9. import "./assets/css/main.css";
  10. export default {
  11. name: "app",
  12. components: {
  13. Quote
  14. }
  15. };
  16. </script>

Then we will update the component to get and store our quote:

  1. <script>
  2. export default {
  3. data() {
  4. return {
  5. quote: null
  6. };
  7. },
  8. methods: {
  9. getNewQuote: function() {
  10. var self = this;
  11. window.backend.Quotes.GetQuote().then(result => {
  12. self.quote = result;
  13. });
  14. }
  15. },
  16. };
  17. </script>

We are simply changing the name of the data element from message to quote, and changing the name of the function we are calling to retrieve the quote. We store it in the quote variable defined in data().

Recap: The quote struct looks like this:

  1. {
  2. text: 'the quote text',
  3. author: 'the quote author'
  4. }

Next, we’ll update the template to use the quote object:

  1. <template>
  2. <div class="container">
  3. <blockquote v-if="quote != null" :cite="quote.author">{{ quote.text }}</blockquote>
  4. <a @click="getNewQuote">Press Me!</a>
  5. </div>
  6. </template>

Let’s look at Line 3. We are using a blockquote element to encapsulate the quote. Within this element, we are using the v-if Vue directive. This will conditionally render the element based on the condition given to it. In our case, this is quote != nil. We will define quote in the component. This will be what stores our quote struct from the backend. The next directive we use is :cite. This simply sets an attribute on the blockquote element. In our case, we are setting it to quote.author. This references the author field of the quote struct we are getting from the backend. Within the element tags, we are using a template directive. This will output text based on the data within the double braces. In our case this will be quote.text.

In Line 4, we simply update the name of the component’s method to call when the button is clicked.

If we serve the project now, we can see something like this:

Quotes Generator - 图6

If we press the button, we can see the quote!

Quotes Generator - 图7

The styling is terrible. Let’s fix that!

Styling the component

We already have some styling in the <style> section of the component. We will update this:

  1. <style scoped>
  2. /**
  3. Credit: https://codepen.io/harmputman/pen/IpAnb
  4. **/
  5. .container {
  6. width: 100%;
  7. max-width: 480px;
  8. min-width: 320px;
  9. margin: 2em auto 0;
  10. padding: 1.5em;
  11. opacity: 0.8;
  12. border-radius: 1em;
  13. border-color: #117;
  14. }
  15. p { margin-bottom: 1.5em; }
  16. p:last-child { margin-bottom: 0; }
  17. blockquote {
  18. display: block;
  19. border-width: 2px 0;
  20. border-style: solid;
  21. border-color: #eee;
  22. padding: 2.5em 0 0.5em;
  23. margin: 1.5em 0;
  24. position: relative;
  25. color: #fffb04;
  26. }
  27. blockquote:before {
  28. content: '\201C';
  29. position: absolute;
  30. top: 0em;
  31. left: 50%;
  32. transform: translate(-50%, -50%);
  33. background: #131313;
  34. width: 3rem;
  35. height: 2rem;
  36. font: 6em/1.08em sans-serif;
  37. color: #eee;
  38. text-align: center;
  39. }
  40. blockquote:after {
  41. content: "\2013 \2003" attr(cite);
  42. display: block;
  43. text-align: right;
  44. font-size: 1.15em;
  45. color: #53cdff;
  46. }
  47. /* https://fdossena.com/?p=html5cool/buttons/i.frag */
  48. a:hover {
  49. font-size: 1.7em;
  50. border-color: blue;
  51. background-color: blue;
  52. color: white;
  53. border: 3px solid white;
  54. border-radius: 10px;
  55. padding: 9px;
  56. cursor: pointer;
  57. transition: 500ms;
  58. }
  59. a {
  60. font-size: 1.7em;
  61. border-color: white;
  62. background-color: #121212;
  63. color: white;
  64. border: 3px solid white;
  65. border-radius: 10px;
  66. padding: 9px;
  67. cursor: pointer;
  68. display: inline-block;
  69. }
  70. </style>

When we reload the app now, we should see something like this:

Quotes Generator - 图8

Pressing the button should yield the following:

Quotes Generator - 图9

Adding more quotes

Whilst Mat’s quote is iconic (and potentially career ending), we are going to add in a few more quotes. What we want is to retrieve a random quote, every time the button is pressed.

To do this, we are going to add a Quote slice to our Quotes struct in our quotes.go file:

  1. // Quotes is our bound Quote Struct
  2. type Quotes struct {
  3. quotes []*Quote
  4. }

We will also create a small function to create and store our quotes:

  1. // AddQuote creates a Quote object with the given inputs and
  2. // adds it to the Quotes collection
  3. func (q *Quotes) AddQuote(text, author string) {
  4. q.quotes = append(q.quotes, &Quote{Text: text, Author: author})
  5. }

Now that we have our helper functions in place, let’s populate the quotes. We can do this in the NewQuotes function:

  1. // NewQuotes creates a new Quotes Struct
  2. func NewQuotes() *Quotes {
  3. result := &Quotes{}
  4. result.AddQuote("Age is an issue of mind over matter. If you don't mind, it doesn't matter", "Mark Twain")
  5. result.AddQuote("Anyone who stops learning is old, whether at twenty or eighty. Anyone who keeps learning stays young. The greatest thing in life is to keep your mind young", "Henry Ford")
  6. result.AddQuote("Wrinkles should merely indicate where smiles have been", "Mark Twain")
  7. result.AddQuote("True terror is to wake up one morning and discover that your high school class is running the country", "Kurt Vonnegut")
  8. result.AddQuote("A diplomat is a man who always remembers a woman's birthday but never remembers her age", "Robert Frost")
  9. result.AddQuote("As I grow older, I pay less attention to what men say. I just watch what they do", "Andrew Carnegie")
  10. result.AddQuote("How incessant and great are the ills with which a prolonged old age is replete", "C. S. Lewis")
  11. result.AddQuote("Old age, believe me, is a good and pleasant thing. It is true you are gently shouldered off the stage, but then you are given such a comfortable front stall as spectator", "Confucius")
  12. result.AddQuote("Old age has deformities enough of its own. It should never add to them the deformity of vice", "Eleanor Roosevelt")
  13. result.AddQuote("Nobody grows old merely by living a number of years. We grow old by deserting our ideals. Years may wrinkle the skin, but to give up enthusiasm wrinkles the soul", "Samuel Ullman")
  14. result.AddQuote("An archaeologist is the best husband a woman can have. The older she gets the more interested he is in her", "Agatha Christie")
  15. result.AddQuote("All diseases run into one, old age", "Ralph Waldo Emerson")
  16. result.AddQuote("Bashfulness is an ornament to youth, but a reproach to old age", "Aristotle")
  17. result.AddQuote("Like everyone else who makes the mistake of getting older, I begin each day with coffee and obituaries", "Bill Cosby")
  18. result.AddQuote("Age appears to be best in four things old wood best to burn, old wine to drink, old friends to trust, and old authors to read", "Francis Bacon")
  19. result.AddQuote("None are so old as those who have outlived enthusiasm", "Henry David Thoreau")
  20. result.AddQuote("Every man over forty is a scoundrel", "George Bernard Shaw")
  21. result.AddQuote("Forty is the old age of youth fifty the youth of old age", "Victor Hugo")
  22. result.AddQuote("You can't help getting older, but you don't have to get old", "George Burns")
  23. result.AddQuote("Alas, after a certain age every man is responsible for his face", "Albert Camus")
  24. result.AddQuote("Youth is when you're allowed to stay up late on New Year's Eve. Middle age is when you're forced to", "Bill Vaughan")
  25. result.AddQuote("Old age is like everything else. To make a success of it, you've got to start young", "Theodore Roosevelt")
  26. result.AddQuote("A comfortable old age is the reward of a well-spent youth. Instead of its bringing sad and melancholy prospects of decay, it would give us hopes of eternal youth in a better world", "Maurice Chevalier")
  27. result.AddQuote("A man growing old becomes a child again", "Sophocles")
  28. result.AddQuote("I will never be an old man. To me, old age is always 15 years older than I am", "Francis Bacon")
  29. result.AddQuote("Age considers youth ventures", "Rabindranath Tagore")
  30. result.AddQuote("s/be/in", "Mat Ryer")
  31. return result
  32. }

The only thing left to do now is to update our GetQuote() method to return a random quote:

  1. // GetQuote returns a quote
  2. func (q *Quotes) GetQuote() *Quote {
  3. return q.quotes[rand.Intn(len(q.quotes))]
  4. }

You will also need to ensure that you import math/rand, if your IDE hasn’t already:

  1. import "math/rand"

Run wails serve again to recompile and serve the app.

Now when we press the button, we get a fabulous quote:

Quotes Generator - 图10

Now with a slight tweak to the CSS, we can make this look even better. In the component CSS, let’s add a margin to the author:

  1. blockquote:after {
  2. content: "\2013 \2003" attr(cite);
  3. display: block;
  4. text-align: right;
  5. font-size: 1.15em;
  6. color: #53cdff;
  7. margin: 1em;
  8. }

Now we have a great looking quotes app:

Quotes Generator - 图11

Building the app

Now that we have the app working, we want to build it as a standalone app. We do this by running wails build. You should now have a quotes executable (or quotes.exe if on Windows).

Quotes Generator - 图12

Running this should run the app. On MacOS, it looks like this:

Quotes Generator - 图13

Pressing the button works as expected:

Quotes Generator - 图14

Packaging the app

Wails provides the ability to package your application into a platform native format. Packaing is indicated by running wails build -p.

MacOS

On MacOS, running wails build -p will generate a .app bundle. If we run this in the quotes project directory you should end up with a quotes.app bundle:

Quotes Generator - 图15

If we open this in finder, you will see your application as a standard Mac app:

Quotes Generator - 图16

Double clicking this will launch the app as expected. Minimising the app to the dock will show you that the icon works as expected:

Quotes Generator - 图17

Of course, it’s unlikely that you’ll want to use the default icon, so Wails makes it easy for you to replace it. Just replace appicon.png with your own icon and rebuild.

There’s a cool icon here which can be used. I made some changes so that it works better on my dark desktop, renamed the icon to appicon.png and rebuilt:

Quotes Generator - 图18

Windows

Due to the nature of Windows, a standard build will also package the app with the default icon. If you run wails build -p it will leave the build artifacts, including the default icon, so that you can customise the build. Make your changes and run wails build again.

Linux

Currently, packing on Linux isn’t supported as it could mean many things. There is the potential to support snap packages in the future.

Exercises

  • See if you can animate the quotes using something like animate.css
  • See if you can pull quotes from the They Said So quotes API from the backend

Summary

Hopefully you now understand how to build and package a basic application using Wails.