Eight things I noticed learning Go as a Node developer
After a few months of Go next to my daily Node.js: goroutines, gofmt, error handling, GOPATH and the things I'm still on the fence about.
Since the Christmas holidays I’ve been writing Go in my spare time. It started with the Go Tour on a rainy afternoon, and by now there’s a small Go program running in production at the startup: a service that receives webhooks from payment providers and puts them on a queue. Sarah agreed on the condition that I could also explain it to the rest of the team. This post is half that explanation.
I come from Node. My brain thinks in callbacks and event loops. This is what stood out.
1. gofmt ends the discussion#
At the startup we have a 60-line JSHint config and at least once a month a discussion about tabs versus spaces or where the comma goes. Go has gofmt. It formats your code one way, and that way is the way. Tabs. Aligned struct fields. Done.
The first day I found that patronising. After a week I wanted it for every language. My editor runs gofmt on every save and I haven’t thought about formatting since. That’s worth more than you’d think.
2. Errors are just values#
No exceptions, no try/catch, no function (err, result) as the first argument. A function returns an error and you look at it.
func loadConfig(path string) (*Config, error) {
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("opening config: %v", err)
}
defer f.Close()
var cfg Config
if err := json.NewDecoder(f).Decode(&cfg); err != nil {
return nil, fmt.Errorf("parsing config: %v", err)
}
return &cfg, nil
}
Yes, you write if err != nil roughly every three lines. Yes, it’s repetitive. But honestly: in Node I also wrote if (err) return callback(err); every three lines, except that I occasionally forgot, and then got an undefined is not a function twenty frames later. In Go, defer makes sure the file gets closed no matter what, and the explicit return values make it very visible when you’re ignoring an error.
3. Goroutines feel like cheating#
The first thing I wrote in Go was a thing that checks a list of URLs concurrently. In Node that looks like this:
var https = require('https');
var urls = ['https://golang.org', 'https://nodejs.org', 'https://github.com'];
var pending = urls.length;
urls.forEach(function (url) {
var start = Date.now();
https.get(url, function (res) {
res.resume();
console.log(url, res.statusCode, (Date.now() - start) + 'ms');
done();
}).on('error', function (err) {
console.log(url, 'ERROR:', err.message);
done();
});
});
function done() {
if (--pending === 0) {
console.log('done');
}
}
You know that pending counter. Or you use async.parallel, or promises with a library like Bluebird. In Go:
package main
import (
"fmt"
"net/http"
"time"
)
type result struct {
url string
status int
took time.Duration
err error
}
func check(url string, out chan<- result) {
start := time.Now()
resp, err := http.Get(url)
if err != nil {
out <- result{url: url, err: err}
return
}
resp.Body.Close()
out <- result{url: url, status: resp.StatusCode, took: time.Since(start)}
}
func main() {
urls := []string{"https://golang.org", "https://nodejs.org", "https://github.com"}
out := make(chan result)
for _, u := range urls {
go check(u, out)
}
for range urls {
r := <-out
if r.err != nil {
fmt.Printf("%-22s ERROR: %v\n", r.url, r.err)
continue
}
fmt.Printf("%-22s %d (%v)\n", r.url, r.status, r.took)
}
fmt.Println("done")
}
check is plain, synchronous code. Put go in front of it and it runs concurrently. The result comes back through a channel. No callbacks, no counter. (Small bonus: for range urls without variables has only been allowed since Go 1.4. Before that you had to write for _ = range urls.)
You still have to pay attention. A channel nobody reads from anymore leaves a goroutine hanging forever. And sharing data between goroutines without a mutex is asking for trouble. go run -race is your friend.
4. One binary#
go build gives you one static file. No node_modules, no “which version of Node is on that server”. Copy, run. For our webhook service that means one scp and an Upstart script.
Cross-compiling from my laptop to Linux is still a bit of a fight, though. You first have to build the toolchain for the target platform:
cd $GOROOT/src
GOOS=linux GOARCH=amd64 ./make.bash --no-clean
I read that this should get easier in an upcoming version. Yes please.
5. GOPATH is strict#
All your Go code has to live in one workspace, under $GOPATH/src/github.com/yourname/project. For someone who has projects scattered all over his disk, that feels like an imposed filing system. I’ve gotten used to it, but I understand everyone who complains about it.
6. Dependency management is… not really there#
go get fetches the latest version of a package, from the master branch. No version numbers, no lockfile. After the luxury of package.json and npm shrinkwrap, that feels like a step back. For now I use godep to pin dependencies and commit them along. It works, but it’s not an official story.
7. The compiler is strict, and that’s good#
An unused import? Compile error. An unused variable? Compile error. The first days it drove me nuts, especially when I quickly wanted to comment something out to debug. Now I find it reassuring: there’s no dead code lying around.
8. I miss generics (a little)#
I’d promised myself not to bring this up, because apparently it’s the only thing the internet talks about when Go comes up. But yes: I’ve twice written almost the same function for a slice of int and a slice of string. In practice it happens less often than I expected, and interface{} solves it if you’re willing to give up some type safety. I still miss them, but it’s not a dealbreaker.
And Node?#
Node stays my day job, and it’s an exciting time: there’s io.js next to Node 0.12 now, and I have no idea how that’s going to play out. For frontend tooling and quick prototypes I’m sticking with JavaScript. But for small, boring, reliable services that run on a server and should never ask for attention again? There, as far as I’m concerned, Go is the better choice.
Next step: convincing the rest of the team that if err != nil is not a character test.