Skip to content

Instantly share code, notes, and snippets.

@garethpaul
Last active October 3, 2017 22:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save garethpaul/f1787cfdc94cd0805aac082bce0f87c8 to your computer and use it in GitHub Desktop.
Save garethpaul/f1787cfdc94cd0805aac082bce0f87c8 to your computer and use it in GitHub Desktop.
Foursquare GoLang Example
package main
import (
"fmt"
"net/http"
"io/ioutil"
"golang.org/x/oauth2"
"golang.org/x/oauth2/foursquare"
)
var (
foursquareOauthConfig = &oauth2.Config{
RedirectURL: "http://localhost:4000/FoursquareCallback",
ClientID: os.Getenv("foursquarekey"),
ClientSecret: os.Getenv("foursquaresecret"),
Endpoint: foursquare.Endpoint,
}
// Some random string, random for each request
oauthStateString = "random"
)
const htmlIndex = `<html><body>
<a href="/FoursquareLogin">Log in with Foursquare</a>
</body></html>
`
func main() {
http.HandleFunc("/", handleMain)
http.HandleFunc("/FoursquareLogin", handleFoursquareLogin)
http.HandleFunc("/FoursquareCallback", handleFoursquareCallback)
fmt.Println(http.ListenAndServe(":4000", nil))
}
func handleMain(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, htmlIndex)
}
func handleFoursquareLogin(w http.ResponseWriter, r *http.Request) {
url := foursquareOauthConfig.AuthCodeURL(oauthStateString)
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
func handleFoursquareCallback(w http.ResponseWriter, r *http.Request) {
state := r.FormValue("state")
if state != oauthStateString {
fmt.Printf("invalid oauth state, expected '%s', got '%s'\n", oauthStateString, state)
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
code := r.FormValue("code")
token, err := foursquareOauthConfig.Exchange(oauth2.NoContext, code)
if err != nil {
fmt.Printf("oauthConf.Exchange() failed with '%s'\n", err)
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
response, err := http.Get("https://api.foursquare.com/v2/users/self/checkins?v=20160815&afterTimestamp=1279044824&oauth_token=" + token.AccessToken)
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
fmt.Fprintf(w, "Content: %s\n", contents)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment