Web Application to Get Trending Hashtags Near a Location

You want to know what is trending on Twitter for a particular geographic area such as the Canada, another country or group of countries, or possibly even the entire world. Twitter's Trends API enables you to get the trending topics for geographic areas that are designated by a Where On Earth (WOE) ID, originally defined by Geo Planet and then maintained by Yahoo!

This is a basic example of web application to get trends near a location using Twitter API.
The Resource URL https://api.twitter.com/1.1/trends/place.json returns the top 50 trending topics for a specific WOEID, if trending information is available for it. Like all other APIs, it returns the trending topics as JSON data, which can be converted to standard Golang objects and then manipulated with list comprehensions or similar techniques.

Register an application under your Twitter account at http://dev.twitter.com/apps and take the required credentials of consumer key, consumer secret, access token, and access token secret, which OAuth application needs to gain account access.

1. Install required package

Package oauth1 provides a Go implementation of the OAuth 1 spec to allow end-users to authorize a client (i.e. consumer) to access protected resources on his/her behalf.

go get github.com/dghubble/oauth1

2. Development

The main function begins with a call to http.HandleFunc, which tells the http package to handle all requests to the web root ("/") with viewHashTagHandler. The function viewHashTagHandler is of the type http.HandlerFunc. It takes an http.ResponseWriter and an http.Request as its arguments.

2.1 Source code of main.go

The function viewHashTagHandler that will able to handle both GET and POST requests.The ParseFiles creates a new Template and parses the template definitions from the hash_tags.html file.

package main

import (

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)

	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)
		country = r.FormValue("country")
		tags := getHashTags(country)
		postPage, _ := template.ParseFiles("hash_tags.html")
		postPage.Execute(w, tags)
		fmt.Fprintf(w, "Unable to get result.")

2.2 Source code of hash_tags.html.

A template file containing the HTML form.

	<title>Trending hash tags</title>
<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>
    <button type="submit">Show Trends</button>

{{ range $key, $value := . }}
   <li>{{ $value }}</li>
{{ end }}

3. Execution

Now launch the application

go run main.go

This will developed a static website on web server on port 8080 on your machine. This also launch your browser navigating to http://localhost:8080.

You will see an output like the image below:

Most Helpful This Week