First Frontend Go Program - Hello World in Browser

As usual, the first program of frontend programming in Go is to show 'Hello World' in your browser. Here I assume you already have basic understanding of JavaScript and DOM manipulation. If not, please read online JavaScript tutorials first.

Install Go and GopherJS

Visit official website of Go programming language. Download and install Go in your working environment. The instructions on the Go official site are very clear. Please follow them to install Go.

Next, visit GopherJS website. If you install Go properly, you can install GopherJS via go get command as follows:

$ go get -u

Note that the current version of Go is 1.9.2, the current master branch of GopherJS must be compiled with Go 1.9 series. If you use Go 1.8 series, you must also use GopherJS 1.8 branch. Otherwise go get command will fail to compile GopherJS.

OK, now we are ready for our first Hello World program.

Hello World via GopherJS

Now we start to write our first frontend program in Go. We prepare the HTML file for the running of JavaScript.

Next, we will write a Go program to call alert() method of window object and show Hello World in pop-up window. We will compile the Go code into JavaScript via GopherJS.

The js.Global here is actually the window object that we use in JavaScript counterpart. You can try the code on GopherJS Playground:

Run Code on GopherJS Playground

The following line in Go:

js.Global.Call("alert", "Hello World")

is actually the same as the following in JavaScript:

alert("Hello World");

Assume the name of previous Go file is app.go, we can compile the Go code to JavaScript by the following command:

$ gopherjs build app.go -o app.js

Put the compiled js file together with HTML and open the HTML with your browser, you will see a pop-up windows with the message Hello World.

Hello World via GopherJS + godom

In above example, we use the syntax directly provided by GopherJS. The syntax is ugly and makes the code difficult to read. I write a package called godom which makes the syntax similar to JavaScript.

Install godom package by the following command:

$ go get -u

Now we use godom to re-write above example as follows:

The program now looks more like JavaScript counterpart and easy to read. Compile and run this program as above. You will see the same result.


This post shows the basic steps of frontend Go programming via GopherJS and godom. I do not recommend to use directly the syntax provided by GopherJS. Instead, to use the syntax provided by godom will make the code more readable.

You can view and download the source code from my GitHub project.

[1]Go Hacker News - A HN client built with GopherJS : golang
[2]Animated QR data transfer with Gomobile and Gopherjs : golang
[3]GitHub - gopherjs/vecty: Vecty: a frontend toolkit for GopherJS : golang