How to Implement Service Discovery in Go

Web
Go lacks native service discovery, requiring external tools like Consul or DNS lookups via the net package to locate services dynamically.

Go does not have a built-in service discovery mechanism; you must implement it using a registry like Consul, Etcd, or a DNS-based approach. For a simple DNS-based lookup, use the net package to resolve hostnames dynamically:

package main

import (
	"fmt"
	"net"
	"time"
)

func main() {
	// Resolve all IPs for a service name (e.g., from DNS or /etc/hosts)
	ips, err := net.LookupIP("my-service.local")
	if err != nil {
		fmt.Println("Discovery failed:", err)
		return
	}
	fmt.Println("Found instances:", ips)
	
	// Retry logic for dynamic updates
	for {
		time.Sleep(30 * time.Second)
		ips, _ = net.LookupIP("my-service.local")
		fmt.Println("Updated instances:", ips)
	}
}