Added ConnectwiseSite struct and method, added GetCompaniesByName method

This commit is contained in:
Steven Polley 2018-06-20 10:55:53 -06:00
parent 0c9c05c62d
commit c21dc9c2cb
2 changed files with 72 additions and 0 deletions

View File

@ -1,6 +1,12 @@
package connectwise
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"time"
)
@ -141,3 +147,40 @@ type Companies []struct {
Value string `json:"value"`
} `json:"customFields"`
}
func GetCompaniesByName(site *ConnectwiseSite, companyName string) *Companies {
companies := Companies{}
//Build the request URL
var Url *url.URL
Url, err := url.Parse(site.Site)
check(err)
Url.Path += "/company/companies"
parameters := url.Values{}
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()
if response.StatusCode != http.StatusOK {
out := fmt.Sprintf("CW API returned HTTP Status Code %s\n%s", response.Status, response.Body)
log.Fatal(out)
} else {
body, err := ioutil.ReadAll(response.Body)
check(err)
check(json.Unmarshal(body, &companies))
}
return &companies
}

View File

@ -0,0 +1,29 @@
package connectwise
import (
"encoding/base64"
"fmt"
"log"
)
type ConnectwiseSite struct {
Site string
Auth string
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
//Returns a ConnectwiseSite struct with the site and auth string available for use in API requests
func NewSite(site string, publicKey string, privateKey string, company string) *ConnectwiseSite {
authString := fmt.Sprintf("%s+%s:%s", company, publicKey, privateKey)
authString = base64.StdEncoding.EncodeToString([]byte(authString))
authString = fmt.Sprintf("Basic %s", authString)
cwSite := ConnectwiseSite{Site: site, Auth: authString}
return &cwSite
}