DEV Community

Cover image for Build a Chat service using GoLang and WebAssembly (part 2)
Taher Fattahi
Taher Fattahi

Posted on • Updated on

Build a Chat service using GoLang and WebAssembly (part 2)

ok, now we want to write our first WebAssembly code with golang

this is our source code structure:
structure

our source code => Github Link


Hello World WebAssembly Program Cross Compiled from Go:

Let's start by writing a simple hello world program in Go, cross compile it to WebAssembly, and run it on the browser.

1) At the first you have to install golang compiler on your device => golang

2) Creating a directory with a new project:

mkdir golangChatWebAssembly 
cd golangChatWebAssembly 
Enter fullscreen mode Exit fullscreen mode

3) Let’s create golangChatWebAssembly module:

go mod init golangChatWebAssembly
Enter fullscreen mode Exit fullscreen mode

4) Let’s create main.go file

mkdir app && cd app
touch main.go
Enter fullscreen mode Exit fullscreen mode

5) Let’s fill our application with content

app/main.go

package main

import (  
    "fmt"
)

func main() {  
    fmt.Println("Go Web Assembly")
}
Enter fullscreen mode Exit fullscreen mode

6) Now it’s time to build our app

This command will compile our go application into the main file. wasm (with wasm bytecode) is an executable module of a web assembly.

if you have Linux or MacOS use bottom command:

GOOS=js GOARCH=wasm go build -o ./html/main.wasm .
Enter fullscreen mode Exit fullscreen mode

if you have Windows OS I suggest creating build.bat file and then running it:

touch build.bat 
Enter fullscreen mode Exit fullscreen mode

on your build.bat file write this syntax:

SET GOOS=js
SET GOARCH=wasm

go build -o ./html/main.wasm .

SET GOOS=windows
SET GOARCH=amd64
Enter fullscreen mode Exit fullscreen mode

and then run it in command line: .\build.bat

7) Javascript Glue

As we already discussed (part 1), WebAssembly is supposed to exist hand in hand with JavaScript. Hence some JavaScript glue code is needed to import the WebAssembly Module we just created and run it in the browser. This code is already available in the Go installation. Let's go ahead and copy it to our html directory.

cp "$(go env GOROOT)/misc/wasm/wasm_exec.js" ./html/  
Enter fullscreen mode Exit fullscreen mode

The above command copies the wasm_exec.js that contains the glue code to run WebAssembly into the html directory.

in Windows OS download wasm_exec.js from this link and then copy file into html folder

8) we have to create a HTML page with an application call to the Web Assembly

create index.html in app/html directory:

<html>
    <head>
        <meta charset="utf-8"/>
        <script src="wasm_exec.js"></script>
        <script>
            if (!WebAssembly.instantiateStreaming) {
                WebAssembly.instantiateStreaming = async (resp, importObject) => {
                    const source = await (await resp).arrayBuffer();
                    return await WebAssembly.instantiate(source, importObject);
                };
            }

            const go = new Go();
            WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject).then(result => {
                go.run(result.instance);
            });
        </script>
    </head>
</html>
Enter fullscreen mode Exit fullscreen mode

9) we will also need a web server

Let’s create a simple web server on Go

cd ..
mkdir server && cd server
touch server.go
Enter fullscreen mode Exit fullscreen mode

fill our server.go with this source code:

package main

import (
    "log"
    "net/http"
)

const (
    AddSrv       = ":8080"
    TemplatesDir = "../app/html/"
)

func main() {
    fileSrv := http.FileServer(http.Dir(TemplatesDir))

    err := http.ListenAndServe(AddSrv, fileSrv)

    if err != nil {
        log.Fatalln(err)
    }
}

Enter fullscreen mode Exit fullscreen mode

10) After that, we start the server

server/

go run server.go
Enter fullscreen mode Exit fullscreen mode

and open the address in the browser

http://127.0.0.1:8080

and in “DevTools > console” you can see the output:

Go Web Assembly

Console.log image


In part 3 we are going to study about chat service architecture 😉

Top comments (2)

Collapse
 
andrewmundy profile image
Andrew Mundy

Excited for the third part of this!

Collapse
 
taherfattahi profile image
Taher Fattahi

Thanks a lot 🙏