Skip to content

Instantly share code, notes, and snippets.

@jingkaihe
Created November 2, 2014 23:40
Show Gist options
  • Save jingkaihe/abf02fef8675b1db995c to your computer and use it in GitHub Desktop.
Save jingkaihe/abf02fef8675b1db995c to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"os"
"fmt"
"log"
"code.google.com/p/goauth2/oauth"
"flag"
"bytes"
)
func confFile() *os.File {
homeDirectory := os.Getenv("HOME")
confFileName := fmt.Sprintf("%s/.spotify/conf.json", homeDirectory)
_confFile, _ := os.Open(confFileName)
return _confFile
}
func cacheFileDirectory() string {
homeDirectory := os.Getenv("HOME")
return fmt.Sprintf("%s/.spotify/cache.json", homeDirectory)
}
func fetchIDandSecret() (string, string) {
type Configuration struct {
ClientID string `json:"ClientID"`
ClientSecret string `json:"ClientSecret"`
}
decoder := json.NewDecoder(confFile())
configuration := Configuration{}
err := decoder.Decode(&configuration)
if err != nil {
log.Panic("error:", err)
}
return configuration.ClientID, configuration.ClientSecret
}
var redirectURL = "http://jaxihjk.me"
var scope= "playlist-read-private playlist-modify-public playlist-modify-private user-library-read user-library-modify user-read-private user-read-email"
var authURL = "https://accounts.spotify.com/authorize"
var tokenURL = "https://accounts.spotify.com/api/token"
var code = flag.String("code", "", "Authorization Code")
var meEndPoint = "https://api.spotify.com/v1/me"
type User struct {
DisplayName string `json:"display_name"`
Email string `json:"email"`
ID string `json:"id"`
Images [] struct {
URL string `json:"url"`
} `json:"images"`
}
func main() {
flag.Parse()
clientID, clientSecret := fetchIDandSecret()
config := &oauth.Config {
ClientId: clientID,
ClientSecret: clientSecret,
RedirectURL: redirectURL,
Scope: scope,
AuthURL: authURL,
TokenURL: tokenURL,
TokenCache: oauth.CacheFile(cacheFileDirectory()),
}
transport := &oauth.Transport{Config: config}
token, err := config.TokenCache.Token()
if err != nil {
if *code == "" {
url := config.AuthCodeURL("")
fmt.Print("Visit this URL to get a code, then run again with -code=YOUR_CODE\n\n")
fmt.Println(url)
return
}
token, err = transport.Exchange(*code)
if err != nil {
log.Panic("Exchange:", err)
}
fmt.Println("Token is cached in %v\n", config.TokenCache)
}
transport.Token = token
response, err := transport.Client().Get(meEndPoint)
if err != nil {
log.Panic("error:", err)
}
defer response.Body.Close()
myInfo := User{}
buf := new(bytes.Buffer)
buf.ReadFrom(response.Body)
json.Unmarshal(buf.Bytes(), &myInfo)
fmt.Println(myInfo.DisplayName)
if len(myInfo.Images) > 0 {
fmt.Println(myInfo.Images[0].URL)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment