You've already forked email-api-client
We Had To Use Dark Magic To Make This Work
This commit is contained in:
99
client/token.go
Executable file
99
client/token.go
Executable file
@@ -0,0 +1,99 @@
|
||||
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)
|
||||
}
|
||||
Reference in New Issue
Block a user