Go-github无法正确获取标签名称

huangapple go评论85阅读模式
英文:

Go-github not retrieving tag names correctly

问题

我有以下简单的 Golang 代码,用于从 Terraform 仓库中获取标签:

import (
	"github.com/google/go-github/v48/github"
	"context"
)

func main() { 
	client := github.NewClient(nil)
	tags, _, _ := client.Repositories.ListTags(context.Background(), "hashicorp", "terraform", nil)
	if len(tags) > 0 {
		latestTag := tags[0]
		fmt.Println(latestTag.Name)
	} else {
		fmt.Printf("No tags yet")
	}
}

它返回一个奇怪的十六进制值:0x1400035c4a0,而我想要返回的是:v1.4.0-alpha20221207

根据官方文档,ListTags 函数应该返回编码为结构体的名称:
https://pkg.go.dev/github.com/google/go-github/github#RepositoriesService.ListTags

非常感谢。

我尝试执行了一个简单的 GET 请求 https://api.github.com/repos/hashicorp/terraform/tags,我可以看到 GitHub API 正确地返回了标签。

英文:

I have the following simple golang code which retrieves tags from terraform repository:

import (
	"github.com/google/go-github/v48/github"
	"context"
)
func main() { 
client := github.NewClient(nil)
	tags, _, _ := client.Repositories.ListTags(context.Background(), "hashicorp", "terraform", nil)
	if len(tags) > 0 {
		latestTag := tags[0]
		fmt.Println(latestTag.Name)
	} else {
		fmt.Printf("No tags yet")
	}
}

Which returns a strange hexadecimal value:
0x1400035c4a0
And I would want to return:
v1.4.0-alpha20221207

Following the official docs, the function ListTags should return the name encoded into a struct:
https://pkg.go.dev/github.com/google/go-github/github#RepositoriesService.ListTags

Many thanks

I did try to execute a simple GET request https://api.github.com/repos/hashicorp/terraform/tags and I can see that the github api returns the tags correctly

答案1

得分: 1

我不知道为什么,但我意识到latestTag.Name是一个指针,你打印的是内存的地址:0x1400035c4a0

你只需要对其进行解引用:

fmt.Println(*latestTag.Name)

额外的,可以使用if条件来检查函数调用返回的error,以避免像这样进行操作:

tags, response, err := client.Repositories.ListTags(context.Background(), "hashicorp", "terraform", nil)

fmt.Println(response)

if err != nil {
	fmt.Println(err)
} else {
	if len(tags) > 0 {
		latestTag := tags[0]
		fmt.Println(*latestTag.Name)
	} else {
		fmt.Printf("No tags yet")
	}
}
英文:

IDK why, but I realize the latestTag.Name is a pointer and what you're printing is the address of the memory: 0x1400035c4a0.

You just need to dereference it:

fmt.Println(*latestTag.Name)

Bonus, check error with if condition that is returned by the function call to avoid having to go something like this:

tags, response, err := client.Repositories.ListTags(context.Background(), "hashicorp", "terraform", nil)

fmt.Println(response)

if err != nil {
	fmt.Println(err)
} else {
	if len(tags) > 0 {
		latestTag := tags[0]
		fmt.Println(*latestTag.Name)
	} else {
		fmt.Printf("No tags yet")
	}
}

huangapple
  • 本文由 发表于 2022年12月18日 07:45:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/74838242.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定