Created method for generic GET request to CW API to handle all the HTTP garbage. Updated methods to use new GetRequest method.

This commit is contained in:
Steven Polley 2018-06-20 14:23:49 -06:00
parent 3c8e0a424f
commit 4e97924700
2 changed files with 18 additions and 24 deletions

View File

@ -3,7 +3,6 @@ package connectwise
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"time"
)
@ -162,17 +161,7 @@ func GetCompaniesByName(site *ConnectwiseSite, companyName string) *Companies {
parameters.Add("conditions", "name=\""+companyName+"\"")
Url.RawQuery = parameters.Encode()
//Build and make the request
client := &http.Client{}
req, err := http.NewRequest("GET", Url.String(), nil)
check(err)
req.Header.Set("Authorization", site.Auth)
req.Header.Set("Content-Type", "application/json")
response, err := client.Do(req)
check(err)
defer response.Body.Close()
body := getHTTPResponseBody(response)
body := GetRequest(site, Url)
check(json.Unmarshal(body, &companies))
return &companies
@ -188,17 +177,7 @@ func GetCompanyByID(site *ConnectwiseSite, companyID int) *Company {
check(err)
Url.Path += fmt.Sprintf("/company/companies/%d", companyID)
//Build and make the request
client := &http.Client{}
req, err := http.NewRequest("GET", Url.String(), nil)
check(err)
req.Header.Set("Authorization", site.Auth)
req.Header.Set("Content-Type", "application/json")
response, err := client.Do(req)
check(err)
defer response.Body.Close()
body := getHTTPResponseBody(response)
body := GetRequest(site, Url)
fmt.Print(string(body))
check(json.Unmarshal(body, &company))

View File

@ -5,10 +5,11 @@ import (
"io/ioutil"
"log"
"net/http"
"net/url"
)
//Checks for HTTP errors, and if all looks good, returns the body of the HTTP response as a byte slice
func getHTTPResponseBody(resp *http.Response) (body []byte) {
func getHTTPResponseBody(resp *http.Response) []byte {
if resp.StatusCode != http.StatusOK {
out := fmt.Sprintf("CW API returned HTTP Status Code %s\n%s", resp.Status, resp.Body)
log.Fatal(out)
@ -20,3 +21,17 @@ func getHTTPResponseBody(resp *http.Response) (body []byte) {
return body
}
}
//Takes a ConnectwiseSite and request URL, and returns the body of the response
func GetRequest(site *ConnectwiseSite, Url *url.URL) []byte {
client := &http.Client{}
req, err := http.NewRequest("GET", Url.String(), nil)
check(err)
req.Header.Set("Authorization", site.Auth)
req.Header.Set("Content-Type", "application/json")
response, err := client.Do(req)
check(err)
defer response.Body.Close()
return getHTTPResponseBody(response)
}