LoginSignup
12
11

More than 5 years have passed since last update.

GoでSpotify APIを使うょ🍼

Posted at

GoでSpotify API、叩きたいですよね

OAuthが面倒

SpotifyはWeb APIを提供していますが、実際に使うにはOAuthの認証フローを踏まなければいけず、面倒臭いです。 Spotify Web API
また、Goの場合レスポンスのJSONに合わせて構造体を定義しなければならず、これもまた面倒です。

ライブラリ作りました

Spotify APIを使う上での面倒な部分をラップしたライブラリを作りました。

gotify: https://github.com/gericass/gotify

仕様

  • gotifyでは3種類あるSpotify APIの認証フローの内、Authorization Code Flowをサポートしています。(全てのエンドポイントが使えるので)
  • 各エンドポイント毎に関数と構造体を定義しています。

導入

  • go get github.com/gericass/gotify
  • サーバーからSpotify APIを叩くにはHTTPS化しなきゃいけないっぽいので証明書を発行

使い方

echo frameworkを使った例

main.go
package main

import (
    "github.com/gericass/gotify"
    "github.com/labstack/echo"
    "github.com/labstack/echo/middleware"
)

const clientID = ""
const clientSecret = ""
const callbackURI = "https://localhost:3000/callback/"

func main() {
    e := echo.New()
    e.Pre(middleware.HTTPSRedirect())
    e.Use(middleware.Logger())
    e.Use(middleware.Recover())

    Auth = gotify.Set(clientID, clientSecret, callbackURI)

    e.GET("/", Handler)
    e.GET("/callback/", CallbackHandler)
    e.GET("/refresh/", RefreshHandler)

    // Require HTTPS
    e.Logger.Fatal(e.StartTLS(":3000", "cert.pem", "key.pem"))
}
handler.go
package main

import (
    "net/http"

    "github.com/labstack/echo"

    "github.com/gericass/gotify"
)

var Auth gotify.OAuth
var Token gotify.Gotify


func Handler(c echo.Context) error {
    url := Auth.AuthURL() // Get the Redirect URL for authenticate
    return c.Redirect(301, url)
}

// CallbackHandler : Controller for https://localhost:3000/callback/
func CallbackHandler(c echo.Context) error {

    t, err := Auth.GetToken(c.Request()) // Get the token for using Spotify API
    if err != nil {
        return err
    }
    Token = t

    return c.String(http.StatusOK, "Authentication success")
}

// RefreshHandler : Controller for https://localhost:3000/refresh/
func RefreshHandler(c echo.Context) error {

    err := Token.Refresh() // Refreshing token for using Spotify API
    if err != nil {
        return err
    }

    return c.String(http.StatusOK, "AccessToken Refreshed")
}
  1. go run $GOROOT/src/crypto/tls/generate_cert.go --host localhostでオレオレ証明書を発行します
  2. Spotify APIのClient ID, Client Secret, Callback URIをセットします
  3. go run main.goを実行します
  4. https://localhost:3000/にアクセスするとログインページにリダイレクトされます
  5. ログインページでログインすると/callback/にリダイレクトされ、APIコール用のトークンが取得できます
  6. トークンを使って各エンドポイントにアクセスできます

サンプル

サンプルアプリケーションを用意しました。⇨ gotifySample

参考

12
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
11