Billy Chandler

Billy Chandler

1584001634

Build PWA with Go and WebAssembly

go-app is a package to build progressive web apps (PWA) with Go programming language and WebAssembly.

It uses a declarative syntax that allows creating and dealing with HTML elements only by using Go, and without writing any HTML markup.

The package also provides an http.handler ready to serve all the required resources to run Go-based progressive web apps.

Install

go-app requirements:

# Init go module (if not initialized):
go mod init

# Get package:
go get -u -v github.com/maxence-charriere/go-app/v6

How it works

app diagram

  • Users: The users of your app. They request pages and resources from their web browser.
  • app.Handler: An http.Handler used by your server or cloud function. It serves your app, its static resources, and all the required files to make it work on user browsers.
  • Application: Your app built with this package. It is built as a WebAssembly (.wasm) binary and is served by the app.Handler.
  • Other static resources: Styles, images, and scripts used by your app. They are also served by the app.Handler.

Declarative syntax

go-app uses a declarative syntax so you can write component-based UI elements just by using the Go programming language.

package main

import "github.com/maxence-charriere/go-app/v6/pkg/app"

type hello struct {
    app.Compo
    name string
}

func (h *hello) Render() app.UI {
    return app.Div().Body(
        app.Main().Body(
            app.H1().Body(
                app.Text("Hello, "),
                app.If(h.name != "",
                    app.Text(h.name),
                ).Else(
                    app.Text("World"),
                ),
            ),
            app.Input().
                Value(h.name).
                Placeholder("What is your name?").
                AutoFocus(true).
                OnChange(h.OnInputChange),
        ),
    )
}

func (h *hello) OnInputChange(src app.Value, e app.Event) {
    h.name = src.Get("value").String()
    h.Update()
}

func main() {
    app.Route("/", &hello{})
    app.Route("/hello", &hello{})
    app.Run()
}

The app is built with the Go build tool by specifying WebAssembly as architecture and javascript as operating system:

GOARCH=wasm GOOS=js go build -o app.wasm

Note that we named the build output app.wasm. The reason is that the HTTP handler requires the web assembly app to be named this way in order to be served.

HTTP handler

Once your app is built, the next step is to serve it.

This package provides an http.Handler implementation ready to serve your PWA and all the required resources to make it work in a web browser.

The handler can be used to create either a web server or a cloud function (AWS Lambda, GCloud function or Azure function).

package main

import (
    "net/http"

    "github.com/maxence-charriere/go-app/v6/pkg/app"
)

func main() {
    h := &app.Handler{
        Title:  "Hello Demo",
        Author: "Maxence Charriere",
    }

    if err := http.ListenAndServe(":7777", h); err != nil {
        panic(err)
    }
}

The server is built as a standard Go program:

go build

Note that you need to add app.wasm to the server location. The reason is that app.Handler is looking for a file named app.wasm in the server directory in order to serve the web assembly binary.

hello-local        # Server directory
├── app.wasm       # Wasm binary
├── hello-local    # Server binary
└── main.go        # Server code

Live apps

luck app hello app city app

#pwa #go #webassembly #wasm

What is GEEK

Buddha Community

Build PWA with Go and WebAssembly
Billy Chandler

Billy Chandler

1584001634

Build PWA with Go and WebAssembly

go-app is a package to build progressive web apps (PWA) with Go programming language and WebAssembly.

It uses a declarative syntax that allows creating and dealing with HTML elements only by using Go, and without writing any HTML markup.

The package also provides an http.handler ready to serve all the required resources to run Go-based progressive web apps.

Install

go-app requirements:

# Init go module (if not initialized):
go mod init

# Get package:
go get -u -v github.com/maxence-charriere/go-app/v6

How it works

app diagram

  • Users: The users of your app. They request pages and resources from their web browser.
  • app.Handler: An http.Handler used by your server or cloud function. It serves your app, its static resources, and all the required files to make it work on user browsers.
  • Application: Your app built with this package. It is built as a WebAssembly (.wasm) binary and is served by the app.Handler.
  • Other static resources: Styles, images, and scripts used by your app. They are also served by the app.Handler.

Declarative syntax

go-app uses a declarative syntax so you can write component-based UI elements just by using the Go programming language.

package main

import "github.com/maxence-charriere/go-app/v6/pkg/app"

type hello struct {
    app.Compo
    name string
}

func (h *hello) Render() app.UI {
    return app.Div().Body(
        app.Main().Body(
            app.H1().Body(
                app.Text("Hello, "),
                app.If(h.name != "",
                    app.Text(h.name),
                ).Else(
                    app.Text("World"),
                ),
            ),
            app.Input().
                Value(h.name).
                Placeholder("What is your name?").
                AutoFocus(true).
                OnChange(h.OnInputChange),
        ),
    )
}

func (h *hello) OnInputChange(src app.Value, e app.Event) {
    h.name = src.Get("value").String()
    h.Update()
}

func main() {
    app.Route("/", &hello{})
    app.Route("/hello", &hello{})
    app.Run()
}

The app is built with the Go build tool by specifying WebAssembly as architecture and javascript as operating system:

GOARCH=wasm GOOS=js go build -o app.wasm

Note that we named the build output app.wasm. The reason is that the HTTP handler requires the web assembly app to be named this way in order to be served.

HTTP handler

Once your app is built, the next step is to serve it.

This package provides an http.Handler implementation ready to serve your PWA and all the required resources to make it work in a web browser.

The handler can be used to create either a web server or a cloud function (AWS Lambda, GCloud function or Azure function).

package main

import (
    "net/http"

    "github.com/maxence-charriere/go-app/v6/pkg/app"
)

func main() {
    h := &app.Handler{
        Title:  "Hello Demo",
        Author: "Maxence Charriere",
    }

    if err := http.ListenAndServe(":7777", h); err != nil {
        panic(err)
    }
}

The server is built as a standard Go program:

go build

Note that you need to add app.wasm to the server location. The reason is that app.Handler is looking for a file named app.wasm in the server directory in order to serve the web assembly binary.

hello-local        # Server directory
├── app.wasm       # Wasm binary
├── hello-local    # Server binary
└── main.go        # Server code

Live apps

luck app hello app city app

#pwa #go #webassembly #wasm

Fannie  Zemlak

Fannie Zemlak

1599854400

What's new in the go 1.15

Go announced Go 1.15 version on 11 Aug 2020. Highlighted updates and features include Substantial improvements to the Go linker, Improved allocation for small objects at high core counts, X.509 CommonName deprecation, GOPROXY supports skipping proxies that return errors, New embedded tzdata package, Several Core Library improvements and more.

As Go promise for maintaining backward compatibility. After upgrading to the latest Go 1.15 version, almost all existing Golang applications or programs continue to compile and run as older Golang version.

#go #golang #go 1.15 #go features #go improvement #go package #go new features

Jake Whittaker

Jake Whittaker

1577384307

Go WebAssembly Tutorial - Building a Calculator Tutorial

In this article, we are going to be building a really simple calculator to give us an idea as to how we can write functions that can be exposed to the frontend, evaluate DOM elements and subsequently update any DOM elements with the results from any functions we call.

This will hopefully show you what it takes to write and compile your own Go-based programs for your frontend applications.

Introduction

So what does this really mean for Go and Web developers? Well, it gives us the ability to write our frontend web apps using the Go language and subsequently all its cool features such as its type safety

Now, this isn’t the first time we’ve seen the Go language being used for frontend purposes. GopherJS has been around for quite a while now and is pretty damn mature, however, the difference is that it compiles Go code to JS and not to WebAssembly.

A Simple Example

Let’s start off with a really simple example, this will simply output Hello World in the console whenever we click a button in our web page. Sounds exciting I know, but we can very quickly build this up into something more functional and cooler:

package main

func main() {
	println("Hello World")
}

Now, in order to compile this, you’ll have to set GOARCH=wasm and GOOS=js and you’ll also have to specify the name of your file using the -o flag like so:

$ GOARCH=wasm GOOS=js go build -o lib.wasm main.go

This command should compile our code into a lib.wasm file within our current working directory. We’ll be using the WebAssembly.instantiateStreaming() function to load this into our page within our index.html. Note - this code was stolen from the official Go language repo:

<!doctype html>
<!--
Copyright 2018 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
<html>

<head>
	<meta charset="utf-8">
	<title>Go wasm</title>
</head>

<body>

	<script src="wasm_exec.js"></script>

	<script>
		if (!WebAssembly.instantiateStreaming) { // polyfill
			WebAssembly.instantiateStreaming = async (resp, importObject) => {
				const source = await (await resp).arrayBuffer();
				return await WebAssembly.instantiate(source, importObject);
			};
		}

		const go = new Go();
		
		let mod, inst;

		WebAssembly.instantiateStreaming(fetch("lib.wasm"), go.importObject).then((result) => {
			mod = result.module;
			inst = result.instance;
			document.getElementById("runButton").disabled = false;
		});

		async function run() {
			await go.run(inst);
			inst = await WebAssembly.instantiate(mod, go.importObject); // reset instance
		}

	</script>

	<button onClick="run();" id="myButton" disabled>Run</button>
</body>
</html>

We’ll also need the wasm_exec.js file which can be found here. Download that and save it alongside your index.html.

$ wget https://github.com/golang/go/blob/master/misc/wasm/wasm_exec.js

And, we also have a simple net/http based file server, again stolen from here, to serve up our index.html and our various other WebAssembly files:

package main

import (
	"flag"
	"log"
	"net/http"
)

var (
	listen = flag.String("listen", ":8080", "listen address")
	dir    = flag.String("dir", ".", "directory to serve")
)

func main() {
	flag.Parse()
	log.Printf("listening on %q...", *listen)
	log.Fatal(http.ListenAndServe(*listen, http.FileServer(http.Dir(*dir))))
}

When you navigate to localhost:8080 once you’ve kicked off this server, you should see that the Run button is clickable and if you open up your console in the browser, you should see that it prints out Hello World every time you click the button!

Awesome, we’ve managed to successfully compile a really simple Go -> WebAssembly project and get it working in the browser.

A More Complex Example

Now for the good bit. Say, we wanted to create a more complex example that featured DOM manipulation, custom Go functions that could be bound to button clicks and more. Well thankfully, it’s not too difficult!

Registering Functions

We’ll start off by creating a few functions of our own that we want to expose to our frontend. I’m feeling rather unoriginal today so these are going to be just add and subtract.

These functions take in an array of type js.Value and use the js.Global().Set() function to set output to equal the result of any calculations done within our function. For good measure, we also print out to the console what the result is as well:

func add(i []js.Value) {
	js.Global().Set("output", js.ValueOf(i[0].Int()+i[1].Int()))
	println(js.ValueOf(i[0].Int() + i[1].Int()).String())
}

func subtract(i []js.Value) {
	js.Global().Set("output", js.ValueOf(i[0].Int()-i[1].Int()))
	println(js.ValueOf(i[0].Int() - i[1].Int()).String())
}

func registerCallbacks() {
	js.Global().Set("add", js.NewCallback(add))
	js.Global().Set("subtract", js.NewCallback(subtract))
}

func main() {
	c := make(chan struct{}, 0)

	println("WASM Go Initialized")
	// register functions
	registerCallbacks()
	<-c
}

You’ll notice that we’ve modified our main function slightly by calling make and creating a new channel. This effectively turns our previously short-lived program into a long-running one. We also call another function registerCallbacks() that acts almost like a router, but instead creates new Callbacks that effectively bind our newly created functions to our frontend.

In order for this to work, we have to very slightly modify the JavaScript code within our index.html to run our program instance as soon as it’s fetched it:

const go = new Go();
let mod, inst;
WebAssembly.instantiateStreaming(fetch("lib.wasm"), go.importObject).then(async (result) => {
	mod = result.module;
	inst = result.instance;
	await go.run(inst)
});

Load this up in your browser once again and you should see that, without any button presses, WASM Go Initialized prints out in the console. This means that everything has worked.

We can then start calling out to these functions from the likes of <button> elements like so:

<button onClick="add(2,3);" id="addButton">Add</button>
<button onClick="subtract(10,3);" id="subtractButton">Subtract</button>

Remove the existing Run button and add these two new buttons to your index.html. When you reload the page in the browser and open up the console, you should be able to see the outputs of this function printing out.

We are slowly but surely starting to get somewhere with this!

Evaluating DOM Elements

So, I guess the next stage, is to start evaluating DOM elements and using their values instead of hard-coded values.

Let’s modify the add() function so that I can pass in 2 ids of <input/> elements and then add the values of these elements like so:

func add(i []js.Value) {
	value1 := js.Global().Get("document").Call("getElementById", i[0].String()).Get("value").String()
	value2 := js.Global().Get("document").Call("getElementById", i[1].String()).Get("value").String()
	js.Global().Set("output", value1+value2)
	println(value1 + value2)
}

We can then update our index.html to have the following code:

<input type="text" id="value1"/>
<input type="text" id="value2"/>

<button onClick="add('value1', 'value2');" id="addButton">Add</button>

If you enter some numeric values into both our inputs and then click the Add button, you should hopefully see a concatenation of the two values print out in the console.

What have we forgotten? We need to parse these string values as int values:

func add(i []js.Value) {
	value1 := js.Global().Get("document").Call("getElementById", i[0].String()).Get("value").String()
	value2 := js.Global().Get("document").Call("getElementById", i[1].String()).Get("value").String()

	int1, _ := strconv.Atoi(value1)
	int2, _ := strconv.Atoi(value2)

	js.Global().Set("output", int1+int2)
	println(int1 + int2)
}

You’ll probably notice that I’m not handling errors here as I’m feeling lazy, and this is just for show.

Try recompiling this code now and reloading your browser, you should notice that if we enter the values 22 and 3 in both our inputs, it successfully outputs 25 in the console.

Manipulating DOM elements

Our calculator wouldn’t be very good if it didn’t actually report the results within our page, so let’s fix that now by taking in a third id that we’ll output the results to:

func add(i []js.Value) {
	value1 := js.Global().Get("document").Call("getElementById", i[0].String()).Get("value").String()
	value2 := js.Global().Get("document").Call("getElementById", i[1].String()).Get("value").String()

	int1, _ := strconv.Atoi(value1)
	int2, _ := strconv.Atoi(value2)

	js.Global().Get("document").Call("getElementById", i[2].String()).Set("value", int1+int2)
}

Finally, let’s update our subtract method:

func subtract(i []js.Value) {
	value1 := js.Global().Get("document").Call("getElementById", i[0].String()).Get("value").String()
	value2 := js.Global().Get("document").Call("getElementById", i[1].String()).Get("value").String()

	int1, _ := strconv.Atoi(value1)
	int2, _ := strconv.Atoi(value2)

	js.Global().Get("document").Call("getElementById", i[2].String()).Set("value", int1-int2)
}

Our finished index.html should look something like this:

<!doctype html>
<!--
Copyright 2018 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
<html>

<head>
	<meta charset="utf-8">
	<title>Go wasm</title>
</head>

<body>

	<script src="wasm_exec.js"></script>

	<script>
		if (!WebAssembly.instantiateStreaming) { // polyfill
			WebAssembly.instantiateStreaming = async (resp, importObject) => {
				const source = await (await resp).arrayBuffer();
				return await WebAssembly.instantiate(source, importObject);
			};
		}

		const go = new Go();
		let mod, inst;
		WebAssembly.instantiateStreaming(fetch("lib.wasm"), go.importObject).then(async (result) => {
			mod = result.module;
			inst = result.instance;
			await go.run(inst)
		});

	</script>

	<input type="text" id="value1"/>
	<input type="text" id="value2"/>

	<button onClick="add('value1', 'value2', 'result');" id="addButton">Add</button>
	<button onClick="subtract('value1', 'value2', 'result');" id="subtractButton">Subtract</button>

	<input type="text" id="result">

</body>

</html>

Conclusion

So, in this tutorial, we managed to learn how we can compile our Go programs into WebAssembly using the new v1.11 of the Go language. We created a really simple calculator that exposes functions from our Go code to our frontend and also does a bit of DOM parsing and manipulation to boot.

Hopefully, you found this article useful/interesting! If you did, then I’d love to hear from you in the comments section below.

#WebAssembly #Go #WebDev

Rachel Cole

Rachel Cole

1566891692

Building full-stack web apps with Go, Vecty and WebAssembly

Many of us have heard of — and maybe written — full-stack web applications. We do them in a variety of different ways, but the common denominator is usually JavaScript and Node.js.

Today, we’re going to break with that tradition and write a complete web applicationfront end and backend – without writing a line of JavaScript. We’ll be comparing the developer experience to JavaScript along the way, but we’re going to be only writing Go for this entire project.

We’ll learn how to build a single page link shortener application with just Go, and we’ll end up with working code that shows it in action.

Prerequisites

Today, we’re going to be focusing on Go so make sure you’ve installed the tooling on your machine. I’m going to assume you have basic knowledge of Go, but check out the free Tour of Go to brush up (or learn!) if you need to.

All the shell commands that I’m going to be showing work on a Mac, but should also work on most Linux systems (including WSL!).

Finally, make sure to clone the repository with the code for this article.

And then you’re good to go, let’s get started!

Getting started

First, we’re going to get the application running locally.

Coming from Webpack and surrounding technologies — which you’d use to build a web app with JavaScript — building and running this application is embarrassingly easy. There’s a front-end and a backend part (more on that below), and you compile both of them with the go tool, which requires no configuration.

First, run the backend server:

$ go run .

Next, build the front end in a new terminal window:

$ cd frontend
$ GOOS=js GOARCH=wasm go build -o ../public/frontend.wasm

Finally, go to https://localhost:8081 in your browser to see the app in action.

How this all works

Like most web apps, our link shortener has a front-end and backend piece. In our app, the backend is just a static server written in Go. All of the magic is in the front-end directory, so let’s start there!

If you’re familiar with React or the DOM, you’ll recognize a lot of the concepts we’ll cover. If not, this stuff will come naturally.

We’re using a new Go framework called Vecty to organize our application. Vecty forces you to break down your app into components and arrange them into a tree. The whole scheme is really similar to HTML and the DOM or React.

Here’s what our app’s high-level components would look like if they were HTML:

  • A h2 for the title of the page
  • A form to enter the link to shorten
  • A div to hold the shortened link (this value is dynamically updated as the user types the link into the above)
  • An a to save the short link

Vecty components are so similar to React that they look like the Go equivalent of JSX, except that they have more parentheses.

Let’s zoom in on one and see how it works. Here’s the code for the form component:

elem.Form(
    elem.Input(vecty.Markup(
        event.Input(func(e *vecty.Event) {
            short := uuid.NewV4().String()[0:5]
            h.shortened = short
            vecty.Rerender(h)
        }),
    )),
)

First, elem.Form and elem.Input on lines 1 and 2 are for the <form> and <input> tags, respectively. Those are both Go functions that take one or more arguments. Each argument is something that goes between the opening and closing HTML tags. For example, the stuff we pass to elem.Form goes in between <form> and </form>. This is what the above Go code would look like in HTML:

<form>
    <input>
    </input>
</form>

Pretty simple, right?

The last piece of code we didn’t look at is that event.Input function. This is an event handler just like in HTML/JavaScript. This function takes in another function, which in this case is roughly an onchange handler. Just like you’d expect, that *vecty.Event argument the handler takes in is roughly the same as the JavaScript event.

The logic to actually shorten the link is all inside this handler, and it’s fairly simple. Here is that code commented thoroughly:

// First, make a new UUID and take the first 5 characters of it.
// This will be our new shortcode
short := uuid.NewV4().String()[0:5]
// Next, write the shortcode to a variable. This variable is shared
// with the <div>, so when we re-render this component, the <div> will
// get updated
h.shortened = short
// Finally, re-render the component so that the <div> gets the new shortcode.
// Unlike React, there's no automatic diff functionality. We tell Vecty
// explicitly which components to re-render.
vecty.Rerender(h)

You get web assembly for free

Vecty can scale to big applications because of this component structure, and we can scale our app as big as we want by adding more components as needed. For example, we can add a component above our current top-level to dynamically route to different sub-components based on the URL. This would be similar to some of the popular react-router implementations.

One final thing to keep in mind is that WASM is not HTML, it’s a full departure from the DOM and everything HTML.

I compared all the components in the last section to HTML tags, but they aren’t! That’s where the big difference between Vecty / WASM and React comes in. We’re compiling our Go code straight to WASM, which represents these components differently from the DOM.

Conclusion

At the end of the day, you get some big benefits from using Go and Vecty to build apps:

  1. You get to think in terms of components and nesting, just like with React and the DOM
  2. You can write as much dynamic logic as you want, right next to your components, all in pure Go
  3. You can share code between the server and client, similar to writing a React client and a Node.js server
  4. You get to take advantage of WASM
  5. Or you can compile your Vecty code to HTML too if you want! That’s a whole other article

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about WebAssembly

WebAssembly: The Future of JS and a Multi-Language Web

Using WebAssembly With Node.js

Get started with WebAssembly using JavaScript

WebAssembly for Web Developers

What is WebAssembly?

Speed, Speed, Speed: JavaScript vs C++ vs WebAssembly

WebAssembly Disrupting JavaScript

WebAssembly: Expectation vs. Reality

#webassembly #go #web-development #mobile-apps

The Best Way to Build a Chatbot in 2021

A useful tool several businesses implement for answering questions that potential customers may have is a chatbot. Many programming languages give web designers several ways on how to make a chatbot for their websites. They are capable of answering basic questions for visitors and offer innovation for businesses.

With the help of programming languages, it is possible to create a chatbot from the ground up to satisfy someone’s needs.

Plan Out the Chatbot’s Purpose

Before building a chatbot, it is ideal for web designers to determine how it will function on a website. Several chatbot duties center around fulfilling customers’ needs and questions or compiling and optimizing data via transactions.

Some benefits of implementing chatbots include:

  • Generating leads for marketing products and services
  • Improve work capacity when employees cannot answer questions or during non-business hours
  • Reducing errors while providing accurate information to customers or visitors
  • Meeting customer demands through instant communication
  • Alerting customers about their online transactions

Some programmers may choose to design a chatbox to function through predefined answers based on the questions customers may input or function by adapting and learning via human input.

#chatbots #latest news #the best way to build a chatbot in 2021 #build #build a chatbot #best way to build a chatbot