Lately, I have been writing Golang (more commonly known as just Go, which is what I’ll be using from here on out) at work, and so far I have been enjoying it a lot! This is a small TIL (Today I Learned) about making Go correctly communicate with services in the local machine like, for instance, Redis, Postgres, or Kafka.
In my particular situation, the project I am working on is running on my machine, however, some of the needed services (Redis, Kafka) are running inside a Docker container. For instance, Redis is accessible via the hostname redis, and likewise for Kafka. Initially, I thought that simply adding the following entries to my etc/hosts files would be enough for the name resolution to work properly:
127.0.0.1 redis kafka
However, the code was still throwing errors because it could not connect to redis or Kafka. Turns out that Go has two ways to perform address name resolution, depending on the operating system it is running on. On OS X (which is my case), Golang uses a different name resolution library called cgo, which is a bit different than the default name resolver. You can see which name resolver your Go program is using by setting the flag GODEBUG with the value netdns=2. Here’s a sample output for my program:
GODEBUG=netdns=1 go run main.go > go package net: hostLookupOrder(redis) = cgo ...
On OSX, applications are not allowed to make direct DNS requests. So, let’s try running the program with the pure Go name resolver:
GODEBUG=netdns=go+2 go run main.go > go package net: GODEBUG setting forcing use of Go’s resolver go > package net: hostLookupOrder(redis) = files,dns
(The + sign is used to tell Go to force a specific name resolver and to show debugging information).
And it works! Since the pure Go name resolver is used, Go accesses local files in the machine to perform name resolutions such as /etc/resolv.conf and /etc/hosts
Nowadays I work at Runtime Revolution as a full-stack software developer. Working here has been, and continues to be, a great learning experience. I’ve matured professionally as a developer, as well as a human being.
Top comments (0)