diff --git a/core/unifi/go.mod b/core/unifi/go.mod index 83d311fb..219ef9dc 100644 --- a/core/unifi/go.mod +++ b/core/unifi/go.mod @@ -3,9 +3,8 @@ module github.com/unifi-poller/unifi go 1.14 require ( - github.com/davecgh/go-spew v1.1.1 + github.com/davecgh/go-spew v1.1.1 // indirect github.com/pkg/errors v0.9.1 - github.com/pmezard/go-difflib v1.0.0 github.com/stretchr/testify v1.4.0 golang.org/x/net v0.0.0-20200625001655-4c5254603344 ) diff --git a/core/unifi/go.sum b/core/unifi/go.sum index d8a6dd57..52fd963e 100644 --- a/core/unifi/go.sum +++ b/core/unifi/go.sum @@ -1,9 +1,12 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= @@ -14,5 +17,7 @@ golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/core/unifi/unifi.go b/core/unifi/unifi.go index 5b3ddd5d..79e0c6a4 100644 --- a/core/unifi/unifi.go +++ b/core/unifi/unifi.go @@ -166,6 +166,21 @@ func (u *Unifi) GetData(apiPath string, v interface{}, params ...string) error { return json.Unmarshal(body, v) } +// PutData makes a unifi request and unmarshals the response into a provided pointer. +func (u *Unifi) PutData(apiPath string, v interface{}, params ...string) error { + start := time.Now() + + body, err := u.PutJSON(apiPath, params...) + if err != nil { + return err + } + + u.DebugLog("Requested %s: elapsed %v, returned %d bytes", + u.URL+u.path(apiPath), time.Since(start).Round(time.Millisecond), len(body)) + + return json.Unmarshal(body, v) +} + // UniReq is a small helper function that adds an Accept header. // Use this if you're unmarshalling UniFi data into custom types. // And if you're doing that... sumbut a pull request with your new struct. :) @@ -182,18 +197,26 @@ func (u *Unifi) UniReq(apiPath string, params string) (req *http.Request, err er return } - // Add the saved CSRF header. - req.Header.Set("X-CSRF-Token", u.csrf) - req.Header.Add("Accept", "application/json") - req.Header.Add("Content-Type", "application/json; charset=utf-8") + u.setHeaders(req, params) - if u.Client.Jar != nil { - parsedURL, _ := url.Parse(req.URL.String()) - u.DebugLog("Requesting %s, with params: %v, cookies: %d", req.URL, params != "", len(u.Client.Jar.Cookies(parsedURL))) - } else { - u.DebugLog("Requesting %s, with params: %v,", req.URL, params != "") + return +} + +// UniReqPut is the Put call equivalent to UniReq +func (u *Unifi) UniReqPut(apiPath string, params string) (req *http.Request, err error) { + switch apiPath = u.path(apiPath); params { + case "": + err = fmt.Errorf("Put with no parameters. Use UniReq()") + default: + req, err = http.NewRequest("PUT", u.URL+apiPath, bytes.NewBufferString(params)) } + if err != nil { + return + } + + u.setHeaders(req, params) + return } @@ -204,6 +227,21 @@ func (u *Unifi) GetJSON(apiPath string, params ...string) ([]byte, error) { return []byte{}, err } + return u.do(req) +} + +// PutJSON uses a PUT call and returns the raw JSON in the same way as GetData +// Use this if you want to change data via the REST API +func (u *Unifi) PutJSON(apiPath string, params ...string) ([]byte, error) { + req, err := u.UniReqPut(apiPath, strings.Join(params, " ")) + if err != nil { + return []byte{}, err + } + + return u.do(req) +} + +func (u *Unifi) do(req *http.Request) ([]byte, error) { resp, err := u.Do(req) if err != nil { return []byte{}, err @@ -227,3 +265,17 @@ func (u *Unifi) GetJSON(apiPath string, params ...string) ([]byte, error) { return body, err } + +func (u *Unifi) setHeaders(req *http.Request, params string) { + // Add the saved CSRF header. + req.Header.Set("X-CSRF-Token", u.csrf) + req.Header.Add("Accept", "application/json") + req.Header.Add("Content-Type", "application/json; charset=utf-8") + + if u.Client.Jar != nil { + parsedURL, _ := url.Parse(req.URL.String()) + u.DebugLog("Requesting %s, with params: %v, cookies: %d", req.URL, params != "", len(u.Client.Jar.Cookies(parsedURL))) + } else { + u.DebugLog("Requesting %s, with params: %v,", req.URL, params != "") + } +} diff --git a/core/unifi/unifi_test.go b/core/unifi/unifi_test.go index 28204201..1ef3725f 100644 --- a/core/unifi/unifi_test.go +++ b/core/unifi/unifi_test.go @@ -56,6 +56,32 @@ func TestUniReq(t *testing.T) { a.EqualValues(k, string(d), "POST parameters improperly encoded") } +func TestUniReqPut(t *testing.T) { + t.Parallel() + a := assert.New(t) + p := "/test/path" + u := "http://some.url:8443" + // Test empty parameters. + authReq := &Unifi{Client: &http.Client{}, Config: &Config{URL: u, DebugLog: discardLogs}} + r, err := authReq.UniReqPut(p, "") + a.NotNil(err, "empty params must produce an error") + + // Test with parameters + k := "key1=value9&key2=value7" + authReq = &Unifi{Client: &http.Client{}, Config: &Config{URL: "http://some.url:8443", DebugLog: discardLogs}} + r, err = authReq.UniReqPut(p, k) + a.Nil(err, "newrequest must not produce an error") + a.EqualValues(p, r.URL.Path, + "the provided apiPath was not added to http request") + a.EqualValues(u, r.URL.Scheme+"://"+r.URL.Host, "URL improperly encoded") + a.EqualValues("PUT", r.Method, "with parameters the method must be POST") + a.EqualValues("application/json", r.Header.Get("Accept"), "Accept header must be set to application/json") + // Check the parameters. + d, err := ioutil.ReadAll(r.Body) + a.Nil(err, "problem reading request body, PUT parameters may be malformed") + a.EqualValues(k, string(d), "PUT parameters improperly encoded") +} + /* NOT DONE: OPEN web server, check parameters posted, more. This test is incomplete. a.EqualValues(`{"username": "user1","password": "pass2"}`, string(post_params), "user/pass json parameters improperly encoded")