Add function to fetch and renew token

This commit is contained in:
2017-06-26 11:15:29 +08:00
parent 7425e6bf3d
commit 7f0febbbab
3 changed files with 64 additions and 9 deletions
+2
View File
@@ -0,0 +1,2 @@
say-it-backend
token.json
+62 -9
View File
@@ -4,12 +4,14 @@ import (
"io/ioutil"
"net/http"
"os"
"time"
"net/url"
"encoding/json"
log "github.com/Sirupsen/logrus"
"github.com/davecgh/go-spew/spew"
"gopkg.in/gin-gonic/gin.v1"
)
@@ -17,6 +19,13 @@ type Token struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
BaseTime time.Time
ExpiresTime time.Time
}
type ViewToken struct {
Token string
ExpiresTime int64
}
var (
@@ -26,13 +35,17 @@ var (
)
func init() {
token = fetchToken()
loadToken()
clientId = os.Getenv("CLIENT_ID")
clientSecret = os.Getenv("CLIENT_SECRET")
if clientId == "" || clientSecret == "" {
log.Fatal("Please set environment variable CLIENT_ID and CLIENT_SECRET")
}
fetchToken()
if shouldFetchToken() {
fetchToken()
}
spew.Dump(token)
}
func main() {
@@ -47,28 +60,68 @@ func landing(c *gin.Context) {
}
func fetchTokenHandler(c *gin.Context) {
if time.Now().After(token.ExpiresTime) {
log.Info("Token expires, try to refresh one.")
// fetchToken()
}
if token != nil {
c.JSON(200, ViewToken{Token: token.AccessToken, ExpiresTime: token.ExpiresTime.Unix()})
return
}
c.JSON(404, gin.H{"message": "No Available Token, please concat the Admin: wahyd4@gmail.com. Thanks!"})
}
func fetchToken() *Token {
params := url.Values{"grant_type": {"client_credentials"}, "client_id": {clientId}, "client_secret": {clientSecret}}
func fetchToken() {
log.Info("Start fetching token")
params := url.Values{}
params.Add("grant_type", "client_credentials")
params.Add("client_id", clientId)
params.Add("client_secret", clientSecret)
resp, err := http.PostForm("https://openapi.baidu.com/oauth/2.0/token", params)
if err != nil {
log.Errorln("Fetch Baidu access token failed" + err.Error())
}
// defer resp.Body.Close()
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
if resp.Status != "200 OK" {
log.Errorln("The response of fetch Baidu access token not success: " + string(body))
// return nil
return
}
var t Token
err = json.Unmarshal(body, &t)
if err != nil {
log.Warnln("Unmarshal json failed: " + err.Error())
log.Warn("Unmarshal json failed: " + err.Error())
}
return &t
t.BaseTime = time.Now()
t.ExpiresTime = token.BaseTime.Add(time.Second * time.Duration(token.ExpiresIn))
writeToFile(&t)
token = &t
}
func writeToFile(token *Token) {
log.Info("Write updated token to file")
tokenJSON, _ := json.Marshal(token)
ioutil.WriteFile("./token.json", tokenJSON, 0644)
}
func loadToken() {
log.Info("Loading token from local file")
tokenString, err := ioutil.ReadFile("./token.json")
if err != nil {
log.Warn("Load json file failed, maybe there " + err.Error())
return
}
var t Token
json.Unmarshal(tokenString, &t)
token = &t
}
func shouldFetchToken() bool {
return token == nil || token.AccessToken == "" || time.Now().After(token.ExpiresTime)
}
View File