-
Notifications
You must be signed in to change notification settings - Fork 299
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #172 from bretanac93/add-cli-example
chore: add sample server side package usage
- Loading branch information
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |