您想知道特定地理区域(例如加拿大、另一个国家或国家集团,甚至可能是整个世界)的Twitter趋势。Twitter的Trends API使你能够获取由Where On Earth(WOE)ID指定的地理区域的热门话题,该ID最初由Geo Planet定义,然后由Yahoo!
这是使用Twitter API获取位置附近趋势的Web应用程序的基本示例。
https://api.twitter.com/1.1/trends/place.json返回特定WOOID的前50个热门主题(如果有可用的热门信息)。与所有其他API一样,它将热门主题作为JSON数据返回,这些数据可以转换为标准Golang对象,然后使用列表推导式或类似技术进行操作。
在http://dev.twitter.com/apps的Twitter帐户下注册应用程序,并获取所需的凭据(使用者密钥、使用者密钥、访问令牌和访问令牌密钥),OAuth应用程序需要这些凭据才能获得帐户访问权限。
安装软件包:
go get github.com/dghubble/oauth1
软件包oauth1提供了OAuth 1规范的Go实现,允许最终用户授权客户端(即消费者)代表他/她访问受保护的资源。
示例代码:main.go
能够处理GET和POST请求的函数viewHashTagHandler。ParseFiles创建一个新模板,并从hash_tags.html文件中解析模板定义。
package main
import (
"encoding/json"
"fmt"
"github.com/dghubble/oauth1"
"html/template"
"io/ioutil"
"net/http"
"strings"
)
func getHashTags(country string) []string {
var listHashTags []string
consumerKey := "xxxxxxxxxxxxxxxxxxx"
consumerSecret := "xxxxxxxxxxxxxxxxxxx"
accessToken := "xxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxx"
accessSecret := "xxxxxxxxxxxxxxxxxxx"
if consumerKey == "" || consumerSecret == "" || accessToken == "" || accessSecret == "" {
panic("Missing required environment variable")
}
config := oauth1.NewConfig(consumerKey, consumerSecret)
token := oauth1.NewToken(accessToken, accessSecret)
httpClient := config.Client(oauth1.NoContext, token)
path := "https://api.twitter.com/1.1/trends/place.json?id=" + country
resp, _ := httpClient.Get(path)
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var JSON = strings.TrimLeft(string(body), "[")
JSON = strings.TrimRight(JSON, "]")
var info map[string]interface{}
json.Unmarshal([]byte(JSON), &info)
trends := info["trends"].([]interface{})
for _, element := range trends {
if trendList, ok := element.(map[string]interface{}); ok {
for key, value := range trendList {
// Filter hashtags started with #
if strings.Contains(key, "name") && strings.Contains(value.(string), "#") {
listHashTags = append(listHashTags, value.(string))
}
}
}
}
return listHashTags
}
func main() {
http.HandleFunc("/", viewHashTagHandler)
http.ListenAndServe(":8080", nil)
}
func viewHashTagHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Error(w, "404 not found.", http.StatusNotFound)
return
}
switch r.Method {
case "GET":
getPage, _ := template.ParseFiles("hash_tags.html")
getPage.Execute(w, r)
case "POST":
var country string
if err := r.ParseForm(); err != nil {
fmt.Fprintf(w, "ParseForm() err: %v", err)
return
}
country = r.FormValue("country")
tags := getHashTags(country)
postPage, _ := template.ParseFiles("hash_tags.html")
postPage.Execute(w, tags)
default:
fmt.Fprintf(w, "Unable to get result.")
}
}
示例代码:hash_tags.html
<html>
<head>
<title>Trending hash tags</title>
</head>
<body>
<form method="POST" action="/">
<select name="country">
<option value="23424848">India</option>
<option value="455830">Brazil</option>
<option value="3369">Canada</option>
<option value="1">Global</option>
</select>
<button type="submit">Show Trends</button>
</form>
<ul>
{{ range $key, $value := . }}
<li>{{ $value }}</li>
{{ end }}
</ul>
</body>
</html>
运行程序:
go run main.go
这将在您机器上的端口8080上的Web服务器上开发一个静态网站。这也会启动您的浏览器导航到http://localhost:8080。