Slide 1

Slide 1 text

Go and Node.js A comparison

Slide 2

Slide 2 text

Nathan Youngman Web developer
 > 21 years

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

• Go microservices • gorilla/mux • sqlx, gocql • Node.js • Feathers • Objection

Slide 5

Slide 5 text

• Vue.js • Shape Detection API • Elixir + Erlang NIF (C) account.alberta.ca

Slide 6

Slide 6 text

• Vue.js • Node.js • GraphQL with Apollo

Slide 7

Slide 7 text

Nathan Youngman Author

Slide 8

Slide 8 text

Edmonton Go edmontongo.org

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

– Brendan Eich “It was also an incredible rush job… I knew there would be mistakes, and there would be gaps, so I made it very malleable as a language.” “a language that was approachable, that you could put directly in the web page”

Slide 11

Slide 11 text

– Ryan Dahl “JavaScript plus asynchronous IO plus some HTTP server stuff would be a cool thing. And I was so excited about that idea that I just worked on it non- stop for the next four years.”

Slide 12

Slide 12 text

No content

Slide 13

Slide 13 text

– Ryan Dahl, creator of Node.js “if you’re building a server, I can’t imagine using anything other than Go”

Slide 14

Slide 14 text

– TJ Holowaychuk, creator of Express.js “If you’re doing distributed work then you’ll find Go’s expressive concurrency primitives very helpful.”

Slide 15

Slide 15 text

Go origins • Unix • grep • UTF-8 encoding Ken Thompson Robert Griesemer • Strongtalk VM • Java HotSpot VM • Codegen for V8 Rob Pike • First window system for Unix • Newsqueak, Limbo (CSP)

Slide 16

Slide 16 text

– Rob Pike “We wanted a language with the safety and performance of statically compiled languages such as C++ and Java, but the lightness and fun of dynamically typed interpreted languages such as Python.”

Slide 17

Slide 17 text

• GCC toolchain Ian Lance Taylor Early gophers Brad Fitzpatrick Russ Cox • Memcached • OpenID • Bell Labs • Tech lead

Slide 18

Slide 18 text

Asynchronous I/O Promises

Slide 19

Slide 19 text

Async/Await const axios = require("axios");
 
 async function fetchHumans(url) {
 const response = await axios.get(url);
 return response.data;
 }

Slide 20

Slide 20 text

Calling an async function const express = require("express");
 const app = express();
 const url = “https://www.google.com/humans.txt";
 const port = 3000; 
 app.get("/", async (req, res) => {
 const data = await fetchHumans(url);
 res.send(data);
 });
 
 app.listen(port, () => {
 console.info(`Listening on ${port}`);
 });

Slide 21

Slide 21 text

Promises all the way down Whoops!
 app.get("/", async (req, res) => {
 const data = await fetchHumans(url);
 res.send(data);
 }); The result: Promise { }

Slide 22

Slide 22 text

Multiple promises const urls = [
 "https://www.google.com/humans.txt",
 "https://www.netflix.com/humans.txt",
 "https://medium.com/humans.txt",
 ];
 
 app.get("/", async (req, res) => {
 const promises = urls.map((url) => fetchHumans(url));
 const data = await Promise.all(promises);
 res.setHeader("content-type", "text/plain");
 res.send(data.join("\n\n"));
 });

Slide 23

Slide 23 text

We need error handling const url = "https://www.moogle.com/humans.txt"; The result: UnhandledPromiseRejectionWarning
 Error: connect ECONNREFUSED

Slide 24

Slide 24 text

Try/Catch app.get("/", async (req, res) => {
 try {
 const data = await fetchHumans(url);
 res.send(data);
 } catch (err) {
 console.error(err.message);
 res.status(502).send("Bad gateway");
 }
 });

Slide 25

Slide 25 text

First error app.get("/", async (req, res) => {
 try {
 const promises = urls.map((url) => fetchHumans(url));
 const data = await Promise.all(promises);
 res.setHeader("content-type", "text/plain");
 res.send(data.join("\n\n"));
 } catch (err) {
 console.error(err.message);
 res.status(502).send("Bad gateway");
 }
 });

Slide 26

Slide 26 text

Asynchronous I/O You may not see it, but it’s there.

Slide 27

Slide 27 text

It looks synchronous package main
 
 import (
 "io"
 "log"
 "net/http"
 )
 
 func fetch(url string) (string, error) {
 r, err := http.Get(url)
 if err != nil {
 return "", err
 }
 defer r.Body.Close()
 b, err := ioutil.ReadAll(r.Body)
 if err != nil {
 return "", err
 }
 return string(b), nil
 }

Slide 28

Slide 28 text

Response writer const url = "https://www.google.com/humans.txt"
 
 func handler(w http.ResponseWriter, req *http.Request) {
 data, err := fetch(url)
 if err != nil {
 log.Print(err)
 w.WriteHeader(http.StatusBadGateway)
 io.WriteString(w, "Bad gateway")
 return
 }
 io.WriteString(w, data)
 }

Slide 29

Slide 29 text

Listen and serve func main() {
 http.HandleFunc("/", handler)
 
 const addr = ":3000"
 log.Printf("Listening on %v", addr)
 log.Fatal(http.ListenAndServe(addr, nil))
 }


Slide 30

Slide 30 text

Concurrency in Go Goroutines and channels

Slide 31

Slide 31 text

Fetch multiple humans.txt package main
 
 import (
 "io"
 "io/ioutil"
 "log"
 "net/http"
 "strings"
 "sync"
 )
 
 var urls = []string{
 "https://www.google.com/humans.txt",
 "https://www.netflix.com/humans.txt",
 "https://medium.com/humans.txt",
 }


Slide 32

Slide 32 text

A synchronous API func handler(w http.ResponseWriter, req *http.Request) {
 data, err := fetchHumans(urls)
 if err != nil {
 log.Print(err)
 w.WriteHeader(http.StatusBadGateway)
 io.WriteString(w, "Bad gateway")
 return
 } 
 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
 io.WriteString(w, strings.Join(data, "\n\n"))
 }


Slide 33

Slide 33 text

Concurrency primitives func fetchHumans(urls []string) ([]string, error) {
 var m sync.Mutex
 var wg sync.WaitGroup
 errChan := make(chan error, 1) 
 resp := make([]string, len(urls))

Slide 34

Slide 34 text

for index, url := range urls {
 wg.Add(1)
 go func(index int, url string) {
 defer wg.Done()
 
 s, err := fetch(url)
 if err != nil {
 select {
 case errChan <- err:
 default:
 }
 return
 }
 m.Lock()
 resp[index] = s
 m.Unlock()
 }(index, url)
 }
 wg.Wait()
 
 select {
 case err := <-errChan:
 return nil, err
 default:
 }
 return resp, nil
 }

Slide 35

Slide 35 text

JavaScript Go Promises Channels Single-threaded* event loop Multiplexed goroutines async/await Appears synchronous Async and Concurrency

Slide 36

Slide 36 text

Language [mis]Features

Slide 37

Slide 37 text

Destructuring const data = {
 latitude: 53.5458874,
 longitude: -113.5034304,
 timezone: "America/Edmonton",
 currently: {
 summary: "Light Snow",
 temperature: 20.33,
 },
 };
 
 const {
 currently: {summary, temperature},
 } = data;
 
 console.info(`${summary} and ${temperature}ºF`);


Slide 38

Slide 38 text

– Brendan Eich on early feature requests “I’d like to compare a number to a string that contains that numeral. And I don’t want to have to change my code to convert the string to a number, or the number to a string. I just want it to work. Can you please make the equals operator just say, Oh this looks like a two, and this looks like a string number two. They’re equal enough.”

Slide 39

Slide 39 text

Language [mis]Features

Slide 40

Slide 40 text

Incomparable if "2" == 2 {
 //
 } The result: invalid operation: "2" == 2 (mismatched types string and int)

Slide 41

Slide 41 text

– Go brand book “Go is an open source programming language that enables the production of simple, efficient, and reliable software at scale.”

Slide 42

Slide 42 text

Mutable iteration variables for index, url := range urls {
 go func(index int, url string) {
 // ..
 }(index, url)
 }

Slide 43

Slide 43 text

JavaScript Go Dynamically typed Statically typed Lenient Strict compiler Prototypes, Classes, Inheritance Types, methods, interfaces First-class functions First-class functions Language

Slide 44

Slide 44 text

Node.js Go prettier gofmt eslint go lint, go vet Babel, TypeScript go build Jest, Chai, Mocha, Jasmine go test Tooling

Slide 45

Slide 45 text

Node.js Go ES6 modules packages NPM packages Go modules Ecosystem

Slide 46

Slide 46 text

Node.js Go HTTP/2 HTTP/2 TLS 1.3 with OpenSSL 1.1.1 TLS 1.3 in Go 1.12 Modern Web

Slide 47

Slide 47 text

Node.js Go Full stack Server-only* Ecosystem Batteries included Small projects* Large projects, large teams I/O bound CPU bound and I/O bound Malleable language Reliability, security Use when

Slide 48

Slide 48 text

programminggo.com

Slide 49

Slide 49 text

Nathan Youngman • nathany.com • [email protected] • @nathany