API

Binding

Having just a web frontend means nothing unless you can interact with the system. Wails enables this through ‘binding’ - making Go code callable from the frontend. There are 2 types of code you can bind to the frontend:

  • Functions
  • Struct Methods

When they are bound, they may be used in the frontend.

Functions

Binding a function is as easy as calling Bind with the function name:

  1. package main
  2. import (
  3. "github.com/wailsapp/wails"
  4. "fmt"
  5. )
  6. func Greet(name string) string {
  7. return fmt.Printf("Hello %s!", name)
  8. }
  9. func main() {
  10. app := wails.CreateApp(&wails.AppConfig{
  11. Width: 1024,
  12. Height: 768,
  13. })
  14. app.Bind(Greet)
  15. app.Run()
  16. }

When this is run, a Javascript function called ‘Greet’ is made available under the global ‘backend’ object. The function may be invoked by calling backend.Greet, EG: backend.Greet("World"). The dynamically generated functions return a standard promise. For this simple example, you could therefore print the result as so: backend.Greet("World").then(console.log).

Type conversion

Scalar types are automatically converted into the relevant Go types. Objects are converted to map[string]interface{}. If you wish to make those concrete types in Go, we recommend you use Hashicorp’s mapstructure.

Example:

Using a default Vue template project, we update main.go to include our struct and callback function:

  1. type MyData struct {
  2. A string
  3. B float64
  4. C int64
  5. }
  6. // We are expecting a javascript object of the form:
  7. // { A: "", B: 0.0, C: 0 }
  8. func basic(data map[string]interface{}) string {
  9. var result MyData
  10. fmt.Printf("data: %#v\n", data)
  11. err := mapstructure.Decode(data, &result)
  12. if err != nil {
  13. // Do something with the error
  14. }
  15. fmt.Printf("result: %#v\n", result)
  16. return "Hello World!"
  17. }

In the frontend, we update the getMessage method in the HelloWorld.vue component to send our object:

  1. getMessage: function() {
  2. var self = this;
  3. var mytestStruct = {
  4. A: "hello",
  5. B: 1.1,
  6. C: 99
  7. }
  8. window.backend.basic(mytestStruct).then(result => {
  9. self.message = result;
  10. });
  11. }

When you run this, you will get the following output:

  1. data: map[string]interface {}{"A":"hello", "B":1.1, "C":99}
  2. Result: main.MyData{A:"hello", B:1.1, C:99}

WARNING: It is recommended that business logic and data structure predominantly preside in the Go portion of your application and updates are sent to the front end using events. Managing state in 2 places leads to a very unhappy life.

Struct Methods

It is possible to bind struct methods to the frontend in a similar way. This is done by binding an instance of the struct you wish to use in the frontend. When this is done, all public methods of the struct will be made available to the frontend. Wails does not attempt, or even believe, that binding data to the frontend is a good thing. Wails views the frontend as primarily a view layer with state and business logic normally handled by the backend in Go. As such, the structs that you bind to the front end should be viewed as a “wrapper” or an “interface” onto your business logic.

Binding a struct is as easy as:

robot.go

  1. package main
  2. import "fmt"
  3. type Robot struct {
  4. Name string
  5. }
  6. func NewRobot() *Robot {
  7. result := &Robot{
  8. Name: "Robbie",
  9. }
  10. return result
  11. }
  12. func (t *Robot) Hello(name string) string {
  13. return fmt.Sprintf("Hello %s! My name is %s", name, t.Name)
  14. }
  15. func (t *Robot) Rename(name string) string {
  16. t.Name = name
  17. return fmt.Sprintf("My name is now '%s'", t.Name)
  18. }
  19. func (t *Robot) privateMethod(name string) string {
  20. t.Name = name
  21. return fmt.Sprintf("My name is now '%s'", t.Name)
  22. }

main.go

  1. package main
  2. import "github.com/wailsapp/wails"
  3. func main() {
  4. app := wails.CreateApp(&wails.AppConfig{
  5. Width: 1024,
  6. Height: 768,
  7. Title: "Binding Structs",
  8. })
  9. app.Bind(NewRobot())
  10. app.Run()
  11. }

When the Robot struct is bound, it is made available at backend.Robot in the frontend. As the robot struct has a public method called Hello, then this is available to call at backend.Robot.Hello. The same is true for the Rename method. The robot struct also has another method called privateMethod, but as that is not public, it is not bound.

Here is a demonstration of how this works by running the app in debug mode and using the inspector:

API - 图1

Struct Initialisation

If your struct has a special initialisation method, Wails will call it at startup. The signature for this method is:

  1. WailsInit(runtime *wails.Runtime) error

This allows you to do some initialisation before the main application is launched.

  1. type MyStruct struct {
  2. runtime *wails.Runtime
  3. }
  4. func (s *MyStruct) WailsInit(runtime *wails.Runtime) error {
  5. // Save runtime
  6. s.runtime = runtime
  7. // Do some other initialisation
  8. return nil
  9. }

If an error is returned, then the application will log the error and shutdown.

The Runtime Object that is passed to it is the primary means for interacting with the application at runtime. It consists of a number of subsystems which provide access to different parts of the system. This is detailed in the Wails Runtime section.

Struct Shutdown

If your struct has a special shutdown method, Wails will call it during application shutdown. The signature for this method is:

  1. WailsShutdown()

This allows you to do clean up any resources when the main application is terminated.

  1. type MyStruct struct {
  2. runtime *wails.Runtime
  3. }
  4. func (s *MyStruct) WailsInit(runtime *wails.Runtime) error {
  5. // Save runtime
  6. s.runtime = runtime
  7. // Allocate some resources...
  8. return nil
  9. }
  10. func (s *MyStruct) WailsShutdown() {
  11. // De-Allocate some resources...
  12. }

Binding Rules

Any Go function (or method) may be bound, so long as it follows the following rules:

  • The function must return 0 - 2 results.
  • If there are 2 return parameters, the last one must be an error type.
  • If you return a struct, or struct pointer, the fields you wish to access in the frontend must have Go’s standard json struct tags defined.

If only one value is returned then it will either be available in the resolve or reject part of the promise depending on if it was an error type or not.

Example 1:

  1. func (m *MyStruct) MyBoundMethod(name string) string {
  2. return fmt.Sprintf("Hello %s!", name)
  3. }

In Javascript, the call to MyStruct.MyBoundMethod will return a promise that will resolve with a string.

Example 2

  1. ...
  2. func (m *MyStruct) AddUser(name string) error {
  3. if m.userExists(name) {
  4. return fmt.Errorf("user '%s' already exists");
  5. }
  6. m.saveUser(name)
  7. return nil
  8. }
  9. ...

In Javascript, the call to MyStruct.MyBoundMethod with a new user name will return a promise that will resolve with no value. A call to MyStruct.MyBoundMethod with an existing user name will return a promise that will reject with the error set to user '$name' already exists.

It’s good practice to return 2 values, a result and an error, as this maps directly to Javascript promises. If you are not returning anything, then perhaps events may be a better fit.

Important Detail!

A very important detail to consider is that all calls to bound Go code are run in their own goroutine. Any bound functions should be authored with this in mind. The reason for this is to ensure that bound code does not block the main event loop in the application, which leads to a frozen UI.