gpt4 book ai didi

json - 在 golang 中为 Places API 使用 HTTP 客户端,解码 JSON 和无效字符

转载 作者:数据小太阳 更新时间:2023-10-29 03:42:43 24 4
gpt4 key购买 nike

我是 Go 的新手,正在学习如何使用它。想要测试点击 Google Places API,但在编写请求时遇到了一些问题。似乎请求通过了,我在体内收到了一些东西,但我无法解码它。我只想看到以字符串形式打印的 json,这样我就可以尝试对其进行解码。感谢您的帮助,谢谢!

type place struct {
Name string `json:candidates`
}

func main() {
places("Grill")
}

func places(inputText string) {
url := "https://maps.googleapis.com/maps/api/place/findplacefromtext/"

placesClient := http.Client{
Timeout: time.Second * 10,
}

req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
log.Fatal(err)
}

req.Header.Set("User-Agent", "Testing how to query API's from parameters")
q := req.URL.Query()
q.Add("key", PLACES_KEY)
q.Add("input", inputText)
q.Add("inputtype", "textquery")
req.URL.RawQuery = q.Encode()
pln(req.URL.String())

res, getErr := placesClient.Do(req)
if getErr != nil {
log.Fatal(getErr)
}

body, readErr := ioutil.ReadAll(res.Body)
if readErr != nil {
log.Fatal(readErr)
}

output := place{}
jsonErr := json.Unmarshal(body, &output)
if jsonErr != nil {
log.Fatal(jsonErr)
}

pln(output)
}

最佳答案

谢谢帮助,终于找到答案了。问题部分出在我对 Places API 的理解上,我输入了 https://maps.googleapis.com/maps/api/place/findplacefromtext/ 但需要确保输入 https://maps.googleapis.com/maps/api/place/findplacefromtext/json 最后的JSON部分指定了返回类型,否则我的 body 不断出现404错误。这可以通过添加来解决:

if res.StatusCode == 404 {
log.Fatal("Hit a 404")
}

此外,如果您只想打印出字节字符串,这对我有用

n := len(body)
s := string(body[:n])

pln(s)

这让您更容易看到正在打印的内容

关于json - 在 golang 中为 Places API 使用 HTTP 客户端,解码 JSON 和无效字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51029868/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com