Created
March 29, 2017 04:50
-
-
Save LillyWu/3463f030462e235540e26631957ab3b6 to your computer and use it in GitHub Desktop.
go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"time" | |
"compress/zlib" | |
"bytes" | |
) | |
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 = "https://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("fail to get", err) | |
} | |
defer resp.Body.Close() | |
fmt.Println("resp body:", resp.Body) | |
body, err := ioutil.ReadAll(resp.Body) | |
fmt.Println("body:", body) | |
re, err := zlib.NewReader(bytes.NewReader(body)) | |
fmt.Println("zlib:", re) | |
enflated, err := ioutil.ReadAll(re) | |
fmt.Println("enflated:", string(enflated)) | |
//r := new(twitterResult) //or &twitterResult{} which returns *twitterResult | |
var r twitterResult | |
err = json.Unmarshal(enflated, &r) | |
if err != nil { | |
log.Fatal("fail to read", err) | |
} | |
c <- r | |
time.Sleep(pauseDuration) | |
} | |
} | |
func displayTweets(c chan twitterResult) { | |
tweets := <-c | |
for _, v := range tweets.Results { | |
fmt.Printf("%v:%v\n", v.Username, v.Text) | |
} | |
} | |
func main() { | |
c := make(chan twitterResult) | |
go retrieveTweets(c) | |
for { | |
displayTweets(c) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment