From 57fc57bd6159bddb1181d031f53281f0524d3fdb Mon Sep 17 00:00:00 2001 From: Yoan VALLET <ext.sopra.yvallet@grandlyon.com> Date: Mon, 11 May 2020 23:49:31 +0200 Subject: [PATCH] Update main.go - handle refresh token --- main.go | 43 +++++++++++++++++++++++++++---------------- 1 file changed, 27 insertions(+), 16 deletions(-) diff --git a/main.go b/main.go index b3a0d13..c6ef60b 100644 --- a/main.go +++ b/main.go @@ -117,14 +117,21 @@ func main() { clientSecret := query.Get("client_secret") code := query.Get("code") grantType := query.Get("grant_type") + refreshToken := query.Get("refresh_token") + fmt.Println(refreshToken) // redirectUri := query.Get("redirect_uri") tokenUrl := "https://gw.hml.api.enedis.fr/v1/oauth2/token" + data := url.Values{} data.Set("client_id", clientId) data.Set("client_secret", clientSecret) data.Set("code", code) data.Set("grant_type", grantType) + if refreshToken != "" { + data.Set("refresh_token", refreshToken) + data.Set("grant_type", "refresh_token") + } client := &http.Client{} req, _ := http.NewRequest("POST", tokenUrl, strings.NewReader(data.Encode())) @@ -137,23 +144,27 @@ func main() { fmt.Println(err) } else { defer response.Body.Close() - // Set Content-Type in response header - w.Header().Add("Content-Type", "application/json") - - // Decode response Body using the defined type "TokenResponse" - data := TokenResponse{} - decodeError := json.NewDecoder(response.Body).Decode(&data) - if decodeError != nil { - http.Error(w, decodeError.Error(), 500) - return + if response.StatusCode >= 200 && response.StatusCode <= 299 { + // Set Content-Type in response header + w.Header().Add("Content-Type", "application/json") + + // Decode response Body using the defined type "TokenResponse" + data := TokenResponse{} + decodeError := json.NewDecoder(response.Body).Decode(&data) + if decodeError != nil { + http.Error(w, decodeError.Error(), 500) + return + } + + // Response with json data + jsonError := json.NewEncoder(w).Encode(data) + if jsonError != nil { + http.Error(w, jsonError.Error(), 500) + return + } + } else { + http.Error(w, http.StatusText(response.StatusCode), response.StatusCode) } - - // Response with json data - jsonError := json.NewEncoder(w).Encode(data) - if jsonError != nil { - http.Error(w, jsonError.Error(), 500) - return - } } }) -- GitLab