Build a Chat service using GoLang and WebAssembly (part 2)
Tags: webassembly, go, chat
Published: 2022-07-15 09:58:00

_ok, now we want to write our first WebAssembly code with golang_

this is our source code structure:
![structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzern2qr9gr7hcqlz4fl.png)

our source code => [Github Link](https://github.com/taherfattahi/golangChatWebAssembly)

---

**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](https://go.dev/dl/)

### 2) Creating a directory with a new project:

```
mkdir golangChatWebAssembly 
cd golangChatWebAssembly 
```

### 3) Let’s create golangChatWebAssembly module:

```
go mod init golangChatWebAssembly
```

### 4) Let’s create main.go file

```
mkdir app && cd app
touch main.go
```

### 5) Let’s fill our application with content
_app/main.go_

```
package main

import (  
    "fmt"
)

func main() {  
    fmt.Println("Go Web Assembly")
}
```

### 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 .
```

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

```
touch build.bat 
```

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
```
and then run it in command line: **.\build.bat**

### 7) Javascript Glue

As we already discussed ([part 1](https://dev.to/taherfattahi/build-a-chat-service-using-golang-and-webassembly-part-1-1pee)), 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/  
```

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 ](https://raw.githubusercontent.com/taherfattahi/golangChatWebAssembly/master/app/html/wasm_exec.js)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>
```

### 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
```

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)
	}
}

```

### 10) After that, we start the server 

_server/_

```
go run server.go
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yl7m0nplsv0lizku26ul.png)

---

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