英文:
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")
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论