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")
}
-
go run $GOROOT/src/crypto/tls/generate_cert.go --host localhost
でオレオレ証明書を発行します - Spotify APIのClient ID, Client Secret, Callback URIをセットします
-
go run main.go
を実行します -
https://localhost:3000/
にアクセスするとログインページにリダイレクトされます - ログインページでログインすると
/callback/
にリダイレクトされ、APIコール用のトークンが取得できます - トークンを使って各エンドポイントにアクセスできます
サンプル
サンプルアプリケーションを用意しました。⇨ gotifySample