dpbfb7119 2013-04-03 10:25
浏览 26
已采纳

转到struct代表Twitter JSON结果

I've bashed up this Go twitter client below, the client still needs some work in terms of displaying the results, I'd like to represent the JSON result http://pastie.org/7298856 as a Go struct, I don't need all the fields in the JSON result, any pointers?

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

type TwitterResult struct{

}

var twitterUrl = "http://search.twitter.com/search.json?q=%23KOT"

func retrieveTweets(c chan<- string) {
    for {
        resp, err := http.Get(twitterUrl)
        if err != nil {
            log.Fatal(err)
        }

        defer resp.Body.Close()
        body, err := ioutil.ReadAll(resp.Body)
        c <- string(body)
    }

}

func displayTweets(c chan string) {
    fmt.Println(<-c)
}

func main() {
    c := make(chan string)
    go retrieveTweets(c)
    for {
        displayTweets(c)
    }

}
  • 写回答

2条回答 默认 最新

  • douyaosi3164 2013-04-03 11:45
    关注

    I found this https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/dNjIs-O64do which is enough to point me in the right direction. Update: my implementation of the code

    package main
    
    import (
        "encoding/json"
        "fmt"
        "io/ioutil"
        "log"
        "net/http"
        "time"
    )
    
    type twitterResult struct {
        Results []struct {
            Text     string `json:"text"`
            Ids      string `json:"id_str"`
            Name     string `json:"from_user_name"`
            Username string `json:"from_user"`
            UserId   string `json:"from_user_id_str"`
        }
    }
    
    var (
      twitterUrl = "http://search.twitter.com/search.json?q=%23UCL"
      pauseDuration = 5 * time.Second
    )
    
    func retrieveTweets(c chan<- *twitterResult) {
        for {
            resp, err := http.Get(twitterUrl)
            if err != nil {
                log.Fatal(err)
            }
    
            defer resp.Body.Close()
            body, err := ioutil.ReadAll(resp.Body)
            r := new(twitterResult) //or &twitterResult{} which returns *twitterResult
            err = json.Unmarshal(body, &r)
            if err != nil {
                log.Fatal(err)
            }
            c <- r
            time.Sleep(pauseDuration)
        }
    
    }
    
    func displayTweets(c chan *twitterResult) {
        tweets := <-c
        for _, v := range tweets.Results {
            fmt.Printf("%v:%v
    ", v.Username, v.Text)
        }
    
    }
    
    func main() {
        c := make(chan *twitterResult)
        go retrieveTweets(c)
        for {
            displayTweets(c)
        }
    
    }
    

    The code works very well, I only wonder if creating a channel that is a pointer to a struct is idiomatic Go.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?