dongtou9934 2018-06-25 18:33
浏览 75
已采纳

在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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?