/
controller.go
60 lines (50 loc) · 1.55 KB
/
controller.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package controllers
import (
"fmt"
"github.com/chances/party-server/cache"
s "github.com/chances/party-server/spotify"
"github.com/gin-gonic/gin"
"github.com/zmb3/spotify"
"golang.org/x/oauth2/clientcredentials"
)
var (
partyCache cache.Store
auth spotify.Authenticator
defaultAuth clientcredentials.Config
)
// SetCache sets the Party cache store used by controllers
func SetCache(c cache.Store) {
partyCache = c
}
// SetSpotifyAuth sets the Spotify client factories used by controllers
func SetSpotifyAuth(spotifyAuth spotify.Authenticator, spotifyDefaultAuth clientcredentials.Config) {
auth = spotifyAuth
defaultAuth = spotifyDefaultAuth
}
// Controller template
type Controller struct {
Cache cache.Store
SpotifyAuth spotify.Authenticator
SpotifyDefaultAuth clientcredentials.Config
}
// Setup a Controller with a Party cache store and Spotify client factories
func (cr *Controller) Setup() {
cr.Cache = partyCache
cr.SpotifyAuth = auth
cr.SpotifyDefaultAuth = defaultAuth
}
// RequestURI gets the full request URI given a Gin request context
func (cr *Controller) RequestURI(c *gin.Context) string {
if c.Request.URL.IsAbs() {
return c.Request.URL.RequestURI()
}
return fmt.Sprintf("http://%s%s", c.Request.Host, c.Request.RequestURI)
}
// ClientFromSession gets a Spotify client from the session's user
func (cr *Controller) ClientFromSession(c *gin.Context) (*spotify.Client, error) {
spotifyClient, err := s.ClientFromSession(c, cr.SpotifyAuth)
if err != nil {
return nil, err
}
return spotifyClient, nil
}