From e7296b0a5b2f8ae089a952dc683009fa3fdd87c6 Mon Sep 17 00:00:00 2001 From: Ben Morrison Date: Wed, 12 Feb 2020 21:11:42 -0500 Subject: [PATCH] bubbling errors up to main() instead of panicking --- cli.go | 22 ++++++++-------------- methods/delete.go | 11 +++++++---- methods/fns.go | 24 ++++++++++++------------ methods/get.go | 21 ++++++++++----------- methods/patch.go | 16 +++++++++------- methods/post.go | 14 ++++++++------ methods/put.go | 11 +++++++---- methods/send.go | 32 ++++++++++++++++---------------- 8 files changed, 77 insertions(+), 74 deletions(-) diff --git a/cli.go b/cli.go index de5ad11..3f174ae 100644 --- a/cli.go +++ b/cli.go @@ -2,7 +2,6 @@ package main import ( "fmt" - "log" "os" mets "github.com/athul/pwcli/methods" @@ -67,8 +66,7 @@ func main() { Usage: "Send a GET request", Flags: getFlags, Action: func(c *cli.Context) error { - mets.Getbasic(c) - return nil + return mets.Getbasic(c) }, }, { @@ -76,8 +74,7 @@ func main() { Usage: "Send a POST Request", Flags: postFlags, Action: func(c *cli.Context) error { - mets.Postbasic(c) - return nil + return mets.Postbasic(c) }, }, { @@ -85,8 +82,7 @@ func main() { Usage: "Send a PUT Request", Flags: postFlags, Action: func(c *cli.Context) error { - mets.Putbasic(c) - return nil + return mets.Putbasic(c) }, }, { @@ -94,8 +90,7 @@ func main() { Usage: "Send a PATCH Request", Flags: postFlags, Action: func(c *cli.Context) error { - mets.Patchbasic(c) - return nil + return mets.Patchbasic(c) }, }, { @@ -103,8 +98,7 @@ func main() { Usage: "Send a DELETE Request", Flags: postFlags, Action: func(c *cli.Context) error { - mets.Deletebasic(c) - return nil + return mets.Deletebasic(c) }, }, { @@ -112,8 +106,7 @@ func main() { Usage: "Test all the Endpoints in the Postwoman Collection.json", //Flags: sendFlag, Action: func(c *cli.Context) error { - mets.ReadCollection(c) - return nil + return mets.ReadCollection(c) }, }, } @@ -126,6 +119,7 @@ func main() { err := app.Run(os.Args) if err != nil { - log.Fatal(err) + c := color.New(color.FgRed).Add(color.Bold) + c.Println(fmt.Sprintf("\n%s", err.Error())) } } diff --git a/methods/delete.go b/methods/delete.go index c54ae16..c5e91ba 100644 --- a/methods/delete.go +++ b/methods/delete.go @@ -12,8 +12,7 @@ import ( func Deletebasic(c *cli.Context) error { url, err := checkURL(c.Args().Get(0)) if err != nil { - fmt.Printf("%s\n", err.Error()) - return nil + return fmt.Errorf("URL validation error: %s", err.Error()) } var jsonStr = []byte(c.String("body")) req, err := http.NewRequest("DELETE", url, bytes.NewBuffer(jsonStr)) @@ -31,10 +30,14 @@ func Deletebasic(c *cli.Context) error { client := &http.Client{} resp, err := client.Do(req) if err != nil { - panic(err) + return fmt.Errorf("Request error: %s", err.Error()) } //defer resp.Body.Close() - s := formatresp(resp) + s, err := formatresp(resp) + if err != nil { + return err + } + fmt.Println(s) return nil } diff --git a/methods/fns.go b/methods/fns.go index 5cdde46..4ef473a 100644 --- a/methods/fns.go +++ b/methods/fns.go @@ -5,7 +5,6 @@ import ( "encoding/json" "fmt" "io/ioutil" - "log" "net/http" "strings" @@ -15,13 +14,18 @@ import ( ) // Formatresp formats the Response with Indents and Colors -func formatresp(resp *http.Response) string { +func formatresp(resp *http.Response) (string, error) { var retbody string heads := fmt.Sprint(resp.Header) c := color.New(color.FgCyan, color.Bold) magenta := color.New(color.FgHiMagenta) yellow := color.New(color.FgHiYellow) + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return "", fmt.Errorf("Error reading response body: %s", err.Error()) + } + str := string(body) if strings.Contains(heads, "json") { var obj map[string]interface{} @@ -39,19 +43,15 @@ func formatresp(resp *http.Response) string { c.Print(key, " : ") magenta.Print(value, "\n") } - var s string - if strings.Contains(heads, "plain") { - s = str - } else { - s = c.Sprint(gohtml.Format(str)) + var s string + if strings.Contains(heads, "plain") { + s = str + } else { + s = c.Sprint(gohtml.Format(str)) } retbody = yellow.Sprintf("\nStatus:\t\t%s\n\nStatusCode:\t%d\n", resp.Status, resp.StatusCode) + fmt.Sprintf("\n%s\n", s) - - } - if err != nil { - log.Println("Error on response.\n[ERRO] -", err) } - return retbody + return retbody, nil } func basicAuth(username, password string) string { diff --git a/methods/get.go b/methods/get.go index d3f97ca..03f90e3 100644 --- a/methods/get.go +++ b/methods/get.go @@ -2,25 +2,20 @@ package methods import ( "fmt" - "log" "net/http" - "os" - "github.com/fatih/color" "github.com/urfave/cli" ) //Getbasic sends a simple GET request to the url with any potential parameters like Tokens or Basic Auth -func Getbasic(c *cli.Context) { +func Getbasic(c *cli.Context) error { var url, err = checkURL(c.Args().Get(0)) if err != nil { - fmt.Printf("%s\n", err.Error()) - os.Exit(0) + return err } req, err := http.NewRequest("GET", url, nil) if err != nil { - log.Println("Error on Request.\nDid you give a correct URL? Try giving that") - os.Exit(0) + return fmt.Errorf("Error creating request: %s", err.Error()) } if c.String("token") != "" { var bearer = "Bearer " + c.String("token") @@ -34,10 +29,14 @@ func Getbasic(c *cli.Context) { client := &http.Client{} resp, err := client.Do(req) if err != nil { - log.Println(color.RedString("Error on response.\nDid you give a correct URL? Try giving that")) + return fmt.Errorf("Error sending request: %s", err.Error()) } - s := formatresp(resp) - fmt.Println(s) + s, err := formatresp(resp) + if err != nil { + return err + } + fmt.Println(s) + return nil } diff --git a/methods/patch.go b/methods/patch.go index e4f62de..a27610b 100644 --- a/methods/patch.go +++ b/methods/patch.go @@ -4,17 +4,15 @@ import ( "bytes" "fmt" "net/http" - "os" "github.com/urfave/cli" ) //Patchbasic sends a basic PATCH request -func Patchbasic(c *cli.Context) { +func Patchbasic(c *cli.Context) error { url, err := checkURL(c.Args().Get(0)) if err != nil { - fmt.Printf("%s\n", err.Error()) - os.Exit(0) + return err } var jsonStr = []byte(c.String("body")) req, err := http.NewRequest("PATCH", url, bytes.NewBuffer(jsonStr)) @@ -32,10 +30,14 @@ func Patchbasic(c *cli.Context) { client := &http.Client{} resp, err := client.Do(req) if err != nil { - panic(err) + return fmt.Errorf("Error sending request: %s", err.Error()) } //defer resp.Body.Close() - s := formatresp(resp) - fmt.Println(s) + s, err := formatresp(resp) + if err != nil { + return err + } + fmt.Println(s) + return nil } diff --git a/methods/post.go b/methods/post.go index 7fbde1e..c64455a 100644 --- a/methods/post.go +++ b/methods/post.go @@ -4,17 +4,15 @@ import ( "bytes" "fmt" "net/http" - "os" "github.com/urfave/cli" ) //Postbasic sends a basic POST request -func Postbasic(c *cli.Context) { +func Postbasic(c *cli.Context) error { url, err := checkURL(c.Args().Get(0)) if err != nil { - fmt.Printf("%s\n", err.Error()) - os.Exit(0) + return err } var jsonStr = []byte(c.String("body")) req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr)) @@ -34,9 +32,13 @@ func Postbasic(c *cli.Context) { client := &http.Client{} resp, err := client.Do(req) if err != nil { - panic(err) + return fmt.Errorf("Error sending request: %s", err.Error()) } //defer resp.Body.Close() - s := formatresp(resp) + s, err := formatresp(resp) + if err != nil { + return err + } fmt.Println(s) + return nil } diff --git a/methods/put.go b/methods/put.go index f11c993..58e9f42 100644 --- a/methods/put.go +++ b/methods/put.go @@ -12,8 +12,7 @@ import ( func Putbasic(c *cli.Context) error { url, err := checkURL(c.Args().Get(0)) if err != nil { - fmt.Printf("%s\n", err.Error()) - return nil + return err } var jsonStr = []byte(c.String("body")) req, err := http.NewRequest("PUT", url, bytes.NewBuffer(jsonStr)) @@ -31,10 +30,14 @@ func Putbasic(c *cli.Context) error { client := &http.Client{} resp, err := client.Do(req) if err != nil { - panic(err) + return fmt.Errorf("Error sending request: %s", err.Error()) } //defer resp.Body.Close() - s := formatresp(resp) + s, err := formatresp(resp) + if err != nil { + return err + } + fmt.Println(s) return nil } diff --git a/methods/send.go b/methods/send.go index 12adaae..3f9cdf8 100644 --- a/methods/send.go +++ b/methods/send.go @@ -5,9 +5,7 @@ import ( "encoding/json" "fmt" "io/ioutil" - "log" "net/http" - "os" "github.com/fatih/color" "github.com/urfave/cli" @@ -43,25 +41,27 @@ type Bpardata struct { } //ReadCollection reads the PostWoman Collection Json File and does the Magic Stuff -func ReadCollection(c *cli.Context) { +func ReadCollection(c *cli.Context) error { data, err := ioutil.ReadFile(c.Args().Get(0)) if string(data) == "" { - fmt.Print("PATH is needed") - os.Exit(0) + return fmt.Errorf("PATH is needed") } if err != nil { - fmt.Print(err) + return err } var jsondat []Colls err = json.Unmarshal([]byte(data), &jsondat) if err != nil { - fmt.Println(err) + return fmt.Errorf("Error parsing JSON: %s", err.Error()) } fmt.Println("Name:\t" + color.HiMagentaString(jsondat[0].Name)) for i := 0; i < len(jsondat[0].Request); i++ { - request(jsondat, i) + err := request(jsondat, i) + if err != nil { + return err + } } - + return nil } func request(c []Colls, i int) error { colors := color.New(color.FgHiRed, color.Bold) @@ -73,14 +73,14 @@ func request(c []Colls, i int) error { if c[0].Request[i].Method == "GET" { out, err := getsend(c, i, "GET") if err != nil { - fmt.Print(err) + return err } methods := color.HiYellowString(c[0].Request[i].Method) fmt.Printf("%s |\t%s |\t%s |\t%s", color.HiGreenString(c[0].Request[i].Name), fURL, methods, out) } else { out, err := sendpopa(c, i, c[0].Request[i].Method) if err != nil { - fmt.Print(err) + return err } methods := color.HiYellowString(c[0].Request[i].Method) fURL := colors.Sprintf(c[0].Request[i].URL + c[0].Request[i].Path) @@ -94,7 +94,7 @@ func getsend(c []Colls, ind int, method string) (string, error) { //fmt.Print(url + " ") req, err := http.NewRequest(method, url, nil) if err != nil { - return "", err + return "", fmt.Errorf("Error creating request: %s", err.Error()) } if c[0].Request[ind].Token != "" { var bearer = "Bearer " + c[0].Request[ind].Token @@ -108,7 +108,7 @@ func getsend(c []Colls, ind int, method string) (string, error) { client := &http.Client{} resp, err := client.Do(req) if err != nil { - log.Println("Error on response.\n[ERRO] -", err) + return "", fmt.Errorf("Error sending request: %s", err.Error()) } //defer resp.Body.Close() //fmt.Print(resp.Header) @@ -127,10 +127,10 @@ func sendpopa(c []Colls, ind int, method string) (string, error) { } req, err := http.NewRequest(method, url, bytes.NewBuffer(jsonStr)) - req.Header.Set("Content-Type", c[0].Request[ind].Ctype) if err != nil { - return "", err + return "", fmt.Errorf("Error creating request: %s", err.Error()) } + req.Header.Set("Content-Type", c[0].Request[ind].Ctype) if c[0].Request[ind].Token != "" { var bearer = "Bearer " + c[0].Request[ind].Token req.Header.Add("Authorization", bearer) @@ -143,7 +143,7 @@ func sendpopa(c []Colls, ind int, method string) (string, error) { client := &http.Client{} resp, err := client.Do(req) if err != nil { - log.Println("Error on response.\n[ERRO] -", err) + return "", fmt.Errorf("Error sending request: %s", err.Error()) } //defer resp.Body.Close() //fmt.Print(resp.Header)