diff --git a/main.go b/main.go index aeb6f8f0429a27ef5c2446e6b5016d87722079f1..b3a0d13094d1be48f3213bff3b1ca06e98060e5d 100644 --- a/main.go +++ b/main.go @@ -3,17 +3,29 @@ package main import ( "flag" "fmt" + "time" "net/http" "net/url" "io/ioutil" "strconv" "strings" + "encoding/json" ) var ( httpPort = flag.Int("http_port", 80, "HTTP port to serve on (defaults to 80)") ) +type TokenResponse struct { + AccessToken string `json:"access_token"` + TokenType string `json:"token_type"` + ExpiresIn int `json:"expires_in"` + RefreshToken string `json:"refresh_token"` + Scope string `json:"scope"` + RefreshTokenIssuedAt string `json:"refresh_token_issued_at"` + IssueAt string `json:"issued_at"` +} + func main() { // Parse the flags flag.Parse() @@ -97,7 +109,7 @@ func main() { }) mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) { - fmt.Println("New token request") + fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "- New token request") query := r.URL.Query() fmt.Println(query) @@ -118,35 +130,30 @@ func main() { req, _ := http.NewRequest("POST", tokenUrl, strings.NewReader(data.Encode())) req.Header.Add("Content-Type", "application/x-www-form-urlencoded") + fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "- Send request to token endpoint", tokenUrl) response, err := client.Do(req) - fmt.Println(response.Status) + fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "- Endpoint response with status", response.Status) if err != nil { fmt.Println(err) } else { defer response.Body.Close() - contents, err := ioutil.ReadAll(response.Body) - if err != nil { - fmt.Println(err) + // 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 } - // Get the response body as a string - fmt.Printf("Response content: %s\n", string(contents)) - - - // pageCode := string([]byte(pageContent[codeStartIndex:codeEndIndex])) - // pageState := string([]byte(pageContent[stateStartIndex:stateEndIndex])) - // pageUsage := string([]byte(pageContent[usageStartIndex:usageEndIndex])) - - // Print out the result - // fmt.Printf("Page code: %s\n", pageCode) - // fmt.Printf("Page state: %s\n", pageState) - // fmt.Printf("Page usage: %s\n", pageUsage) - - // state := strings.Split(pageState, "-")[0] - // host := strings.Split(pageState, "-")[1] - - // redir := "https://" + host + "/accounts/enedisoauth/redirect?code=" + pageCode + "&state="+ state +"&usage_point_id=" + pageUsage - // fmt.Println(redir) - // http.Redirect(w, r, redir, 302) + + // Response with json data + jsonError := json.NewEncoder(w).Encode(data) + if jsonError != nil { + http.Error(w, jsonError.Error(), 500) + return + } } })