从Go中的URL进行JSON解码

从Go中的URL进行JSON解码

问题描述:

I have my php code. How to create something like this in Go?

<?php
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$context = stream_context_create(array(
  'http' => array(
     'ignore_errors'=>true,
     'method'=>'GET'
   )
));
$response = json_decode(file_get_contents($url, false, $context));

print_r($response);
?>

Something like this:

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
)

func main() {
    resp, err := http.Get("https://api.twitter.com/1.1/search/tweets.json")
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    fmt.Printf("%#v
", resp)

    dec := json.NewDecoder(resp.Body)
    if dec == nil {
        panic("Failed to start decoding JSON data")
    }

    json_map := make(map[string]interface{})
    err = dec.Decode(&json_map)
    if err != nil {
        panic(err)
    }

    fmt.Printf("%v
", json_map)
}