From 4303069fd0d9cfb053be2f09566df15b216026c7 Mon Sep 17 00:00:00 2001 From: Hugo <hnouts@grandlyon.com> Date: Wed, 16 Sep 2020 16:45:13 +0200 Subject: [PATCH] parse enedis code containing status code when error strconv.Atoi string code into int status code --- main.go | 48 ++++++++++++++++++++++++++++++++++++------------ 1 file changed, 36 insertions(+), 12 deletions(-) diff --git a/main.go b/main.go index 8345153..bc3dc7c 100644 --- a/main.go +++ b/main.go @@ -50,6 +50,20 @@ func LookupEnvOrInt(key string, defaultVal int) int { return defaultVal } +func findItem(arrayType interface{}, item interface{}) bool { + arr := reflect.ValueOf(arrayType) + if arr.Kind() != reflect.Array { + panic("Invalid data-type") + } + for i := 0; i < arr.Len(); i++ { + if arr.Index(i).Interface() == item { + return true + } + } + + return false +} + func main() { // Parse the flags flag.Parse() @@ -127,21 +141,31 @@ func main() { code := query.Get("code") req_state := query.Get("state") + statusCodes := [4]string{"400", "403", "500", "503"} - splitIndex := strings.Index(req_state, "-") - if splitIndex == -1 { - log.Warning("No host found") - } - state := req_state[0:splitIndex] - host := req_state[splitIndex+1:] + if (findItem(statusCodes, code)) { + intCode, err := strconv.Atoi(code) + if err != nil { + log.Print("status code string to int error: ", err) + } + log.Print("status code error : ", code) + http.Error(w, http.StatusText(intCode), intCode) + } else { + splitIndex := strings.Index(req_state, "-") + if splitIndex == -1 { + log.Warning("No host found") + } + state := req_state[0:splitIndex] + host := req_state[splitIndex+1:] - usagePointId := query.Get("usage_point_id") + usagePointId := query.Get("usage_point_id") - cozyURL := "https://" + host + "." + *cozyDomain + *cozyRedirectURI + cozyURL := "https://" + host + "." + *cozyDomain + *cozyRedirectURI - redir := cozyURL + "?code=" + code + "&state=" + state + "&usage_point_id=" + usagePointId - log.Debug("Redirect to -", redir) - http.Redirect(w, r, redir, 302) + redir := cozyURL + "?code=" + code + "&state=" + state + "&usage_point_id=" + usagePointId + log.Debug("Redirect to -", redir) + http.Redirect(w, r, redir, 302) + } }) mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) { @@ -241,7 +265,7 @@ func main() { data.Set("grant_type", "refresh_token") } - log.Debug("Send request to token endpoint", tokenUrl) + log.Debug("Send request to token endpoint: ", tokenUrl) response, err := http.PostForm(tokenUrl, data) if err != nil { log.Error(err) -- GitLab