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() {

func places(inputText string) {
url := ""

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

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

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()

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

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

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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 but need to make sure to put 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])

    this allows you to see what is being printed easier

    点赞 打赏 评论

相关推荐 更多相似问题