Creating a Service
Services are the backbone of your application. They handle business logic and manage state.
In this guide, we’ll create a new service that generates QR codes from text. This will show you how to organize your code into reusable services and handle external dependencies.
-
Create the QR Service file
Create a new file called
qrservice.go
in your application directory and add the following code:
-
Register the Service
Update your
main.go
to use the new QR service:
-
Update go.mod
Update your
go.mod
dependencies to include thegithub.com/skip2/go-qrcode
package:
-
Generate the Bindings
To call these methods from your frontend, we need to generate bindings. You can do this by running
wails generate bindings
in your project root directory.Once you’ve run this, you should see something similar to the following in your terminal:
You should notice that in the frontend directory, there is a new directory called
bindings
:
-
Understanding the Bindings
Let’s look at the generated bindings in
bindings/changeme/qrservice.js
:We can see that the bindings are generated for the
GenerateQRCode
method. The parameter names have been preserved, as well as the comments. JSDoc has also been generated for the method to provide type information to your IDE.The bindings provide:
- Functions that are equivalent to your Go methods
- Automatic conversion between Go and JavaScript types
- Promise-based async operations
- Type information as JSDoc comments
-
Use Bindings in Frontend
Firstly, update
frontend/src/main.js
to use the new bindings:Now update
index.html
to use the new bindings in theinitializeQRGenerator
function:Run
wails3 dev
to start the dev server. After a few seconds, the application should open.Type in some text and click the “Generate QR Code” button. You should see a QR code in the center of the page:
-
Alternative Approach
So far, we have covered the following areas:
- Creating a new Service
- Generating Bindings
- Using the Bindings in our Frontend code
If the aim of your service is to serve files/assets/media to the frontend, like a traditional web server, then there is an alternative approach to achieve the same result.
If your service defines Go’s standard http handler function
ServeHTTP(w http.ResponseWriter, r *http.Request)
, then it can be made accessible on the frontend. Let’s extend our QR code service to do this:Now update
main.go
to specify the route that the QR code service should be accessible on:Finally, update
main.js
to make the image source the path to the QR code service, passing the text as a query parameter:Running the application again should result in the same QR code: