Golang Video Tutorial: Go for JavaScript Developers

In this video I propose to introduce you to the Go language for JavaScript developers. The objective is to make analogies to show you the particularities of languages ​​and broaden your horizons.

00:00 Presentation
02:00 Basic structure
05:14 Syntax of go
08:19 Pointers
10:19 Arrays and Slices
17:38 Object vs Map
19:19 Structures
20:50 Methods
22:54 Interfaces
25:30 Contact an API & parse JSON
33:50 Goroutine
39:38 Create a web server
46:43 Use third-party libraries
49:20 Closing

What is Go

Go is a language that was created by Google engineers (Robert Griesemer, Rob Pike, and Ken Thompson) with the objective of replacing the C++ language with which they encountered problems (too much complexity and too long compilation times notably). It offers several advantages:

  • Simple syntax that is easy to write and read
  • A static typing
  • Fast compile time (even for large projects)
  • Native competition management
  • A substantial standard library to answer most problems

Analogies with JavaScript

Rather than give you a complete presentation of the language, which you can find on the Tour of go anyway, I thought it would be interesting to tell you about the key points that differentiate this language from others.

No export

In JavaScript we export the elements explicitly within a file

export const mafonction = () => {}

In the framework of Go things are more original because all elements starting with a capital letter will be automatically exported. Breakage is therefore of particular importance.

A trainer included

Go includes by default a code formatting tool that avoids discussions around a choice of conventions.

go fmt .

Array & Slice

In Go there is an additional type to manage arrays for better memory management.

a := [3]{1, 2, 3} // C'est un tableau
b := a[1:] // C'est un slice, qui pointe vers le tableau original a
b[1] = 3 // Cela modifie aussi la valeur de a

Slices will be attached to an array and it is important to understand the distinction and the effect this can have when manipulating data.

Error management

In Javascript, errors are managed as in many languages ​​with the use of try / catch

function MaFonction () {
  try {
    codeQuiCrash()
  } catch (e) {
    console.error('Une erreur est survenue')
  }
}

In go functions can have multiple return values ​​and this feature will be used when an operation might encounter an error.

func MaFonction () (string, error) {
  resp, err := http.Get("https://grafikart.fr/api/posts.json")
  if err != nil {
    return "", fmt.Errorf("impossible de contacter le serveur, %w", err)
  }

  b, err := io.ReadAll(resp.Body)
    if err != nil {
    return "", fmt.Errorf("impossible de lire le contenu de la réponse, %w", err)
    }

  return string(b), nil
}

Even if this choice ends up being quite verbose, it is interesting because it forces developers to manage errors rather than letting them escalate unchecked.

Asynchronous management

In JavaScript, asynchronous is managed through asynchronous functions that can wait for a return from the event loop. During this wait, JavaScript will be able to take care of other things which allows, even on a single thread, to be able to manage more things.

async function handleRequest () {
  const r = await fetch("https://grafikart.fr/api").then(r => r.json())
  console.log("response: ", r))
}
handleRequest();
console.log("Je serais affiché avant la réponse")

Go has a goroutine system that allows you to run a function on a very light separate thread managed by Go

func main () {
  wg := new(sync.WaitGroup)
  wg.Add(1)
  go func () {
    defer wg.Done()
    r, err := CustomHTTPGet("https://grafikart.fr/api")
    fmt.Println(r)
  }()
  fmt.Println("Je serais affiché avant la réponse")
  wg.Wait()
}

To communicate with these goroutine, Go offers a channel system

func main () {
  ch := make(chan string)
  go func () {
    r, err := CustomHTTPGet("https://grafikart.fr/api")
    ch <- r
  }()
  fmt.Println("Je serais affiché avant la réponse")
  fmt.Println(<- ch)
}

Goroutines offer many more possibilities but are also a very important source of new problems compared to what we know in JavaScript:

  • It will be necessary to ensure that 2 goroutine does not access the same memory space via mutexes
  • It will also be necessary to make sure not to leave a goroutine running for nothing

Goroutines are also used by default on the HTTP server provided by go, so you don’t have to worry about them most of the time in this kind of use case.