Let's Go

What is Go?

The main Go website http://golang.org describes Go as:

Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.

Go was created by Rob Pike, Ken Thompson, Robert Griesemer and Russ Cox. The reason for creating a new language is detailed in the Go FAQ (https://golang.org/doc/faq\):

Go was born out of frustration with existing languages and environments for systems programming. Programming had become too difficult and the choice of languages was partly to blame. One had to choose either efficient compilation, efficient execution, or ease of programming; all three were not available in the same mainstream language. Programmers who could were choosing ease over safety and efficiency by moving to dynamically typed languages such as Python and JavaScript rather than C++ or, to a lesser extent, Java.

Go is an attempt to combine the ease of programming of an interpreted, dynamically typed language with the efficiency and safety of a statically typed, compiled language. It also aims to be modern, with support for networked and multicore computing. Finally, working with Go is intended to be fast: it should take at most a few seconds to build a large executable on a single computer. To meet these goals required addressing a number of linguistic issues: an expressive but lightweight type system; concurrency and garbage collection; rigid dependency specification; and so on. These cannot be addressed well by libraries or tools; a new language was called for.

From my own experience with Go I have found it to be a very powerful yet simple language, one where you don't get bogged down in the complexity of the language and a forest of abstraction, but a language you can write then come back to at a later time and quickly understand the code.

Go is a relatively small language, with just 25 keywords, comparing this to some other programming languages we see:

  • Go - 25 keywords

  • Java - 50 keywords

  • JavaScript (es6) - 63 keywords

  • C# - 104 keywords

Why Should I use Go?

node.js vs Go

If you are a node.js developer, here are some of the main differences between developing a node.js app and a Go app:

Compiled vs. Interpreted

I don't want to call JavaScript an interpreted language, since being interpreted vs node.js apps are written using JavaScript, which is an interpreted language. The code is

No exceptions

Goroutines, no event loop

Who am I and why do I use Go?

I've been writing software for way longer than I care to admit, starting on lighting automation software running on servers powering huge convention and sports stadiums, then moving on to the Microsoft Windows Display Driver team, working with graphics drivers, then into more of a research role, integrating lab type explorations with feature teams within Microsoft. My last journey led me to a startup where we used node.js for pretty much everything, web servers, api servers, command line tooling and I was hooked.

Why use go?

//TODO:

Go is what I call my "forever language" and I could be wrong about this, but ...

//TODO: go steady, slower pace, solid, simple

Installing

Installing Go is simple, just head over to the downloads page on the main website https://golang.org/dl/ and run the required installer. As of when this book was written, Go is currently at version 1.7 and runs on the following platforms:

  • Windows

  • Linux

  • OS X

  • FreeBSD

The Linux variant also supports the ARMv6 processor architecture, which makes it great to run on a low cost computer like a Raspberry PI (https://www.raspberrypi.org/\), this makes Go, coupled with its strong networking and concurrency model a great choice for building applications like Home Automation servers. This is one thing I have been working on in my spare time, if you like Home Automation you should check it out: https://github.com/markdaws/gohome

Once you have installed go, you should be able to run:

go env

from the command line to make sure that everything is working, if it is you will see something like:

GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/Users/mark/code/go"
GORACE=""
GOROOT="/usr/local/go"
GOTOOLDIR="/usr/local/go/pkg/tool/darwin_amd64"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"

For now don't worry about the variables or values, just that the go executable ran and printed some content to show it was working, we will come back to some of the above values later.

Go Workspaces

Please make sure you don't skip this section, it is fundamental to everything you do to understand a Go workspace.

Folder Structure

A workspace is a special directory structure used by Go and its tooling. Typically Go developers just have one workspace for all their projects but it is possible to have more than one. A workspace is a folder on disk that contains three top level sub directories:

  • src: Contains all of your Go source code

  • pgk: Contains package objects

  • bin: Contains executables built from your source code

GOPATH Environment Variable

Folder Structure

Working on multiple projects

Hello World

One of the first examples of node.js code you will see if the simple http server, which accepts any request on port 3000 and returns a simple "Hello World" string back to the client:

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

The Go equivalent would be:

package main

import (
    "fmt"
    "net/http"
)

const hostname = "127.0.0.1"
const port = ":3000"

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("hi there"))
    })

    fmt.Printf("Server running at http://%s%s", hostname, port)
    http.ListenAndServe(hostname+port, nil)
}

To run this example, type the following in your terminal (assuming you saved the above in a file called server.go):

go run server.go

The next chapter goes in to the Go language syntax in more detail, but we will quickly discuss the main parts of interest in the code above:

package main

All Go code lives in packages. In this case the code is in a package called main.

import (
    "fmt"
    "net/http"
)

The import statement signifies that we want to use code from other packages, in this case the "fmt" package that it used to print output to the terminal

func main() {

In Go, functions are declared using the "func" keyword, this is a simple function with no parameters and no return values, it's special in that Go looks for a function called "main" in the "main" package as the entry point for the executable.

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("hi there"))
})

Just like in the node code where we specify a handler, here we see we specify a handler to the path "/" which will match the root path "/" and all child paths, so basically everything. By default you don't have to set the status code or content type header since the http package tries to infer what it will be.

Another interesting item, is the "*http.Request" parameter, as you can see the "*" denotes this is a pointer, Go supports pointers.

The last thing to note is that we pass a "[]byte("hi there")" value to the Write function, this casts the string to a byte slice. The syntax might make it look like an array in other languages, but it's actually called a slice in Go, which you can think of as a lightweight reference to parts of an arrays content.

goformat/goimports

results matching ""

    No results matching ""