I'm trying to write a simple code in GO that lists all the folders under an organisation in GCP using the resourcemanager API. Below is my code:
package main
import (
"context"
"log"
resourcemanager "cloud.google.com/go/resourcemanager/apiv2"
"google.golang.org/api/iterator"
resourcemanagerpb "google.golang.org/genproto/googleapis/cloud/resourcemanager/v2"
)
func main() {
ctx := context.Background()
c, err := resourcemanager.NewFoldersClient(ctx)
if err != nil {
// TODO: Handle error.
log.Println("Error: Failed to start client.")
}
defer c.Close()
req := &resourcemanagerpb.ListFoldersRequest{
Parent: "organizations/<MY-ORG-NAME>",
}
it := c.ListFolders(ctx, req)
tries := 0
for {
resp, err := it.Next()
if err == iterator.Done || tries == 3 {
break
}
if err != nil {
log.Println(err)
}
// TODO: Use resp.
log.Println(resp)
tries
}
}
The code is directly copied from the API documentation, I just added my organisation name, added some log features and limited the tries in the for loop, since it was endlessly printing errors.
I'm getting the following error messages whenever I run the code:
2021/11/04 17:06:41 rpc error: code = Unimplemented desc = unexpected HTTP status code received from server: 404 (Not Found); transport: received unexpected content-type "text/html; charset=UTF-8"
I'm not sure if this is the solution but; I think I need to add a .proto
file in my directory for it to work, but I didn't understand how to do that or what exactly to put in there. I'm new to GO and it's my first time working with API's so this all seems very confusing to me.
Any help is very much appreciated!
CodePudding user response:
Migrating to the API v3 solved the problem. This works perfectly!
Thank you to everyone who commented and to my coworker who found the solution!
package main
import (
"context"
"fmt"
"log"
cloudresourcemanager "google.golang.org/api/cloudresourcemanager/v3"
)
func main() {
ctx := context.Background()
svc, err := cloudresourcemanager.NewService(ctx)
if err != nil {
log.Fatal(err)
}
foldersService := cloudresourcemanager.NewFoldersService(svc)
foldersListCall := foldersService.List()
foldersListCall.Parent("organizations/<MY-ORG-ID>")
resp, err := foldersListCall.Do()
if err != nil {
log.Fatal(err)
}
for _, fld := range resp.Folders {
fmt.Println(fld.DisplayName)
}
}