Unable to import LXD as module in GOLANG

Hi Folks,

I’m having a bit of trouble with getting a simple go program to use the canonical LXD module. While I can do a go get command and it seems to work, I am unable to do a go mod tidy.

 + go.mod _______________________________________________________________________________________________________________________________________________________________
[fedora simple]$ go get github.com/canonical/lxd
go: added github.com/canonical/lxd v0.0.0-20230915202554-8185f8a7acc1
[fedora simple]$ go mod tidy
go: finding module for package github.com/canonical/lxd
simple imports
	github.com/canonical/lxd: module github.com/canonical/lxd@latest found (v0.0.0-20230915202554-8185f8a7acc1), but does not contain package github.com/canonical/lxd
[fedora simple]$ go run main.go
main.go:5:2: no required module provides package github.com/canonical/lxd; to add it:
	go get github.com/canonical/lxd
[fedora simple]$

Here is the code:

package main

import (
	"fmt"
	"github.com/canonical/lxd"
)

func main() {
	client, err := lxd.client.ConnectLxd("", nil)
	if err != nil {
		fmt.Printf("Error: %s\n", err)
		return
	}

	instances, err := client.GetInstanceNames(api.InstanceTypeContainer)
	if err != nil {
		fmt.Printf("Error: %s\n", err)
		return
	}
	for _, inst := range instances {
		fmt.Printf("Instance Name: %s\n", inst)
	}
	fmt.Print("Done")
}

I can’t figure out why this error occurs and have been working on it for a couple of days. Is there something simple I’m missing here? Any pointers are much appreciated.

Jason

When you go get github.com/canonical/lxd it works because this is the go module. Go mod tidy works by resolving the packages that you are using from the modules you have added. In this case, github.com/canonical/lxd is a module but not a package (this is just the top level of the git repo). The client package is found in github.com/canonical/lxd/client, so your code should look like:

package main

import (
	"fmt"

	lxd "github.com/canonical/lxd/client"
	"github.com/canonical/lxd/shared/api"
)

func main() {
	client, err := lxd.ConnectLXD("", nil)
	if err != nil {
		fmt.Printf("Error: %s\n", err)
		return
	}

	instances, err := client.GetInstanceNames(api.InstanceTypeContainer)
	if err != nil {
		fmt.Printf("Error: %s\n", err)
		return
	}

	for _, inst := range instances {
		fmt.Printf("Instance Name: %s\n", inst)
	}

	fmt.Print("Done")
}

Note that this will still not work because the address of the LXD server is empty. If you are using a local snap install of LXD you can use lxd.ConnectLXDUnix and set the address to /var/snap/lxd/common/lxd/unix.socket. You will need to run the go program with sudo or under the lxd group for this to work.

2 Likes