dongtou9934
2018-06-25 18:33
浏览 72

在golang,Unmarshal JSON和无效字符中使用HTTP Client for Places API

I am pretty new to Go, learning how to use it. Wanted to test hitting the Google Places API, but am having some trouble in writing the request. It seems the request goes through, I receive something in the body, but I cannot Unmarshall it. I just want to see the json printed in string form so I can try to decode it. Any help is appreciated, thank you!

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)
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongshan4549 2018-06-25 18:45
    已采纳

    Thank you for the help, ended up finding the answer. The issue was partly with my understanding of the Places API, I had entered https://maps.googleapis.com/maps/api/place/findplacefromtext/ but need to make sure to put https://maps.googleapis.com/maps/api/place/findplacefromtext/json The JSON part at the end specifies the return type, otherwise my body was constantly getting 404 errors. This can be fixed by adding:

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

    Also, if you just want to print out the byte string, this worked for me

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

    this allows you to see what is being printed easier

    点赞 打赏 评论

相关推荐 更多相似问题