retry only once for refreshing JWT

This commit is contained in:
Anish Mukherjee 2022-12-09 19:55:27 +05:30
parent 94dc0d9c8a
commit 98e60edb19

View file

@ -29,7 +29,7 @@ func getAuthToken(ctx config.Context, force bool) string {
log.Fatalf("Client could not read response body: %s", err) log.Fatalf("Client could not read response body: %s", err)
} }
if res.StatusCode != http.StatusOK { if res.StatusCode != http.StatusOK {
log.Fatalf("Error response: %s", string(resBodyBytes)) log.Fatalf("Error Status: %d Response: %s", res.StatusCode, string(resBodyBytes))
} }
body := new(models.SuccessResponse) body := new(models.SuccessResponse)
if err := json.Unmarshal(resBodyBytes, body); err != nil { if err := json.Unmarshal(resBodyBytes, body); err != nil {
@ -67,14 +67,16 @@ func request[T any](method, route string, payload any) *T {
} else { } else {
req.Header.Set("Authorization", "Bearer "+getAuthToken(ctx, false)) req.Header.Set("Authorization", "Bearer "+getAuthToken(ctx, false))
} }
retried := false
retry: retry:
res, err := http.DefaultClient.Do(req) res, err := http.DefaultClient.Do(req)
if err != nil { if err != nil {
log.Fatalf("Client error making http request: %s", err) log.Fatalf("Client error making http request: %s", err)
} }
// refresh JWT token // refresh JWT token
if res.StatusCode == http.StatusUnauthorized { if res.StatusCode == http.StatusUnauthorized && !retried {
req.Header.Set("Authorization", "Bearer "+getAuthToken(ctx, true)) req.Header.Set("Authorization", "Bearer "+getAuthToken(ctx, true))
retried = true
goto retry goto retry
} }
resBodyBytes, err := io.ReadAll(res.Body) resBodyBytes, err := io.ReadAll(res.Body)
@ -82,7 +84,7 @@ retry:
log.Fatalf("Client could not read response body: %s", err) log.Fatalf("Client could not read response body: %s", err)
} }
if res.StatusCode != http.StatusOK { if res.StatusCode != http.StatusOK {
log.Fatalf("Error Status: %d Response: %s", http.StatusOK, string(resBodyBytes)) log.Fatalf("Error Status: %d Response: %s", res.StatusCode, string(resBodyBytes))
} }
body := new(T) body := new(T)
if len(resBodyBytes) > 0 { if len(resBodyBytes) > 0 {