Skip to content

Instantly share code, notes, and snippets.

@ajstarks
Last active October 10, 2015 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajstarks/3760929 to your computer and use it in GitHub Desktop.
Save ajstarks/3760929 to your computer and use it in GitHub Desktop.
Go Twitter Command line client
// ts -- twitter search
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
)
type JTweets struct {
Results []Result
}
type Result struct {
From_user string
From_user_name string
Text string
}
var (
nresults = flag.Int("n", 20, "Maximum results (up to 100)")
since = flag.String("d", "", "Search since this date (YYYY-MM-DD)")
)
const (
queryURI = "http://search.twitter.com/search.json?q=%s&rpp=%d"
)
// ts queries twitter via the search API
func ts(s string, date string, n int) {
var q string
if len(date) > 0 {
q = fmt.Sprintf(queryURI+"&since=%s", url.QueryEscape(s), n, date)
} else {
q = fmt.Sprintf(queryURI, url.QueryEscape(s), n)
}
r, err := http.Get(q)
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
return
}
defer r.Body.Close()
if r.StatusCode == http.StatusOK {
readjson(r.Body)
} else {
fmt.Fprintf(os.Stderr,
"Twitter is unable to search for %s (%s)\n", s, r.Status)
}
}
// readjson reads and decodes the JSON response from twitter
func readjson(r io.Reader) {
var twitter JTweets
b, err := ioutil.ReadAll(r)
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
return
}
jerr := json.Unmarshal(b, &twitter)
if jerr != nil {
fmt.Fprintf(os.Stderr, "Unable to parse the JSON feed (%v)\n", jerr)
return
}
for _, t := range twitter.Results {
fmt.Printf("%-25s @%-15s %s\n", t.From_user_name, t.From_user, t.Text)
}
}
func main() {
flag.Parse()
for _, s := range flag.Args() {
ts(s, *since, *nresults)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment