Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mentor Review | Output and Error Handling | Mohammed Suara #249

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions projects/output-and-error-handling/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/CodeYourFuture/immersive-go-course/projects/output-and-error-handling

go 1.21.5
61 changes: 61 additions & 0 deletions projects/output-and-error-handling/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package main

import (
"fmt"
"io"
"net/http"
"os"
"strconv"
"time"
)

func main() {

client := &http.Client{Timeout: time.Duration(1) * time.Second}

response, err := client.Get("http://localhost:8080")
if err != nil {
fmt.Fprint(os.Stderr, "Server is down. Please try again later\t")
os.Exit(1)
}

defer response.Body.Close()

if response.StatusCode == http.StatusOK {
body, err := io.ReadAll(response.Body)
if err != nil {
fmt.Fprint(os.Stderr, "Response body could not be read: ", err)
os.Exit(2)
}
fmt.Fprintln(os.Stdout, string(body))
} else if response.StatusCode == http.StatusTooManyRequests {
handleRetry(response)
} else {
fmt.Fprintf(os.Stderr, "Unexpected response: %d\n", response.StatusCode)
os.Exit(4)
}


}

func handleRetry(res *http.Response) {

retryHeader := res.Header.Get("Retry-After")
parsedTime, err := http.ParseTime(retryHeader)
if err == nil {
waitTime := time.Until(parsedTime)
fmt.Printf("You have to wait for %vsecs to restart the application", int64(waitTime/time.Second))
time.Sleep(waitTime)
} else {
waitSecs, err := strconv.Atoi(retryHeader)
if err == nil {
fmt.Printf("You have to wait for %dsecs to start the application again", waitSecs)
time.Sleep(time.Duration(waitSecs) * time.Second)
} else {
fmt.Fprint(os.Stderr, "Invalid Retry Header!!!\t")
os.Exit(3)
}
}

defer res.Body.Close()
}