Skip to content

Commit

Permalink
Merge pull request #172 from bretanac93/add-cli-example
Browse files Browse the repository at this point in the history
chore: add sample server side package usage
  • Loading branch information
strideynet authored Oct 21, 2021
2 parents bb40ef1 + 1cf9f9a commit 40fdc53
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions examples/cli/cli.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package cli

import (
"context"
"flag"
"github.com/zmb3/spotify/v2"
spotifyauth "github.com/zmb3/spotify/v2/auth"
"golang.org/x/oauth2"
"log"
)

var auth = spotifyauth.New(spotifyauth.WithRedirectURL("http://localhost:3000/login_check"))

func main() {
code := flag.String("code", "", "authorization code to negotiate by token")
flag.Parse()

if *code == "" {
log.Fatal("code required")
}
if err := Authorize(*code); err != nil {
log.Fatal("error while negotiating the token: ", err)
}
}

func Authorize(code string) error {
ctx := context.Background()
token, err := auth.Exchange(ctx, code)
httpClient := oauth2.NewClient(context.Background(), oauth2.StaticTokenSource(token))
client := spotify.New(httpClient)

user, err := client.CurrentUser(ctx)
if err != nil {
return err
}
log.Printf("Logged in as %s\n", user.DisplayName)

return nil
}

0 comments on commit 40fdc53

Please sign in to comment.