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

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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!