2013-07-18 93 views
2

我有我的php代碼。如何在Go中創建這樣的內容?來自url的JSON解碼在

<?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); 
?> 
+0

看一看如何使一個GET請求http://golang.org/pkg/net/http/和http://golang.org/pkg/encoding/json /如何解碼接收的json。 – Volker

回答

4

事情是這樣的:

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\n", 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\n", json_map) 
} 
+0

如何向陣列中的URL添加其他參數?例如:'https://api.twitter.com/1.1/search/tweets.json?code = 253&demo = 32535' – leliwa19

+0

@ leliwa19你是什麼意思的數組參數?看看這個 - http://play.golang.org/p/zFfiMy2C0i。請注意,您需要自行轉義密鑰和值以保持URL有效。 –

+0

請注意,您需要關閉res.Body。 – Dustin