100 lines
1.8 KiB
Go
Executable File
100 lines
1.8 KiB
Go
Executable File
package client
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"git.siteworxpro.com/golang/packages/email-api/redis"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
type Token struct {
|
|
AccessToken string `json:"access_token"`
|
|
TokenType string `json:"token_type"`
|
|
ExpiresIn uint16 `json:"expires_in"`
|
|
}
|
|
|
|
type AccessTokenRequest struct {
|
|
GrantType string `json:"grant_type"`
|
|
ClientId string `json:"client_id"`
|
|
ClientSecret string `json:"client_secret"`
|
|
}
|
|
|
|
func NewToken(config *Configuration) *Token {
|
|
|
|
return &Token{}
|
|
}
|
|
|
|
func getToken(configuration *Configuration) (*Token, error) {
|
|
|
|
token := FromCache()
|
|
|
|
if token.AccessToken != "" {
|
|
return token, nil
|
|
}
|
|
|
|
request := accessTokenRequest{
|
|
GrantType: "client_credentials",
|
|
ClientId: configuration.ClientId,
|
|
ClientSecret: configuration.ClientSecret,
|
|
}
|
|
|
|
body, _ := json.Marshal(request)
|
|
|
|
resp, err := http.Post(configuration.Endpoint+"/access_token", "application/json", bytes.NewBuffer(body))
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
responseBody := make([]byte, resp.ContentLength)
|
|
_, err = resp.Body.Read(responseBody)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
err = json.Unmarshal(responseBody, token)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
saveCache(token)
|
|
|
|
return token, nil
|
|
}
|
|
|
|
func FromCache() *Token {
|
|
rdb := redis.NewRedis()
|
|
|
|
token := Token{}
|
|
|
|
result, err := rdb.Get(context.Background(), "api.access_token").Result()
|
|
if err != nil {
|
|
return &token
|
|
}
|
|
|
|
err = json.Unmarshal([]byte(result), &token)
|
|
if err != nil {
|
|
return &token
|
|
}
|
|
|
|
return &token
|
|
}
|
|
|
|
func saveCache(token *Token) {
|
|
rdb := redis.NewRedis()
|
|
|
|
tokenJson, _ := json.Marshal(token)
|
|
|
|
expiresIn := time.Duration(int64(token.ExpiresIn) * 100000000)
|
|
|
|
cmd := rdb.Set(context.Background(), "api.access_token", tokenJson, expiresIn)
|
|
result, err := cmd.Result()
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
println(result)
|
|
}
|