From d4a9537b5671fafe04335b9f91c5d5869d4a2358 Mon Sep 17 00:00:00 2001 From: Teddy Wing Date: Sun, 4 Jun 2017 00:38:28 +0200 Subject: Move HTTP response body errors into http.go Take the errors in `main()` that check the response body contents for known error strings and put them in their respective functions in "timetask/http.go". Didn't really make sense to me that these functions were returning HTTP responses that we weren't really using in a meaningful way. Instead they should just do their thing and let us know if there was a problem. That includes checking to see if there were any non-standard errors, like the ones we had custom-built. Now all that handling and error-making is self-contained, which feels much nicer. --- timetask/http.go | 51 +++++++++++++++++++++++++++++++++++---------------- 1 file changed, 35 insertions(+), 16 deletions(-) (limited to 'timetask') diff --git a/timetask/http.go b/timetask/http.go index 575ceae..f0a6548 100644 --- a/timetask/http.go +++ b/timetask/http.go @@ -15,18 +15,14 @@ import ( var baseURL string = "https://af83.timetask.com/index.php" -func Login(username, password string) ( - resp *http.Response, - client *http.Client, - err error, -) { +func Login(username, password string) (client *http.Client, err error) { cookies, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List}) if err != nil { - return nil, nil, err + return nil, err } client = &http.Client{Jar: cookies} - resp, err = client.PostForm( + resp, err := client.PostForm( baseURL, url.Values{ "module": {"people"}, @@ -37,30 +33,53 @@ func Login(username, password string) ( }, ) if err != nil { - return resp, client, err + return client, err } - return resp, client, err + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return client, err + } + + if strings.Contains( + string(body), + "The username and password don't appear to be valid.", + ) { + return client, fmt.Errorf("TimeTask authentication failed") + } + + return client, err } -func SubmitTimeEntry( - client http.Client, - time_entry TimeEntry, -) (resp *http.Response, err error) { +func SubmitTimeEntry(client http.Client, time_entry TimeEntry) error { values := buildSubmissionParams(time_entry) values.Set("module", "time") values.Set("action", "submitmultipletime") - resp, err = client.PostForm( + resp, err := client.PostForm( baseURL, values, ) if err != nil { - return resp, err + return err + } + + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return err + } + + if strings.Contains( + string(body), + "No time entries were created.", + ) { + return fmt.Errorf("time entry creation failed") } - return resp, nil + return nil } func buildSubmissionParams(time_entry TimeEntry) url.Values { -- cgit v1.2.3