From 6ff00a84519adf87ac6ad94c04739b5e00a4f2c4 Mon Sep 17 00:00:00 2001 From: maciej palczynski Date: Mon, 30 Aug 2021 16:54:36 +0200 Subject: [PATCH 1/6] Configure golangci-lint and adjust the code to comply --- .github/workflows/test.yml | 2 +- .golangci.yml | 119 +++++++++++++- apiv6/kentikapi/client.go | 2 + apiv6/kentikapi/client_integration_test.go | 62 ++++--- apiv6/kentikapi/httputil/httputil.go | 1 + apiv6/kentikapi/httputil/httputil_test.go | 30 +++- apiv6/localhost_apiserver/main.go | 22 ++- examples/custom_applications_example_test.go | 2 + examples/demos/retry_demo/main.go | 10 +- go.mod | 2 + go.sum | 17 ++ kentikapi/client.go | 54 +++---- kentikapi/internal/api_resources/alerting.go | 62 ------- .../api_resources/custom_applications.go | 62 ------- .../api_resources/custom_dimensions.go | 114 ------------- .../internal/api_resources/device_labels.go | 85 ---------- kentikapi/internal/api_resources/devices.go | 152 ------------------ .../api_resources/my_kentik_portal.go | 60 ------- kentikapi/internal/api_resources/plans.go | 31 ---- kentikapi/internal/api_resources/query.go | 78 --------- .../internal/api_resources/saved_filters.go | 67 -------- kentikapi/internal/api_resources/sites.go | 85 ---------- .../rest_client.go | 37 +++-- .../stub_transport.go | 4 +- .../transport.go | 2 +- .../{api_endpoints => endpoints}/alerting.go | 9 +- .../custom_applications.go | 2 +- .../custom_dimensions.go | 2 +- .../device_labels.go | 2 +- .../{api_endpoints => endpoints}/devices.go | 2 +- .../my_kentik_portal.go | 2 +- .../{api_endpoints => endpoints}/plans.go | 2 +- .../{api_endpoints => endpoints}/query.go | 2 +- .../saved_filters.go | 2 +- .../{api_endpoints => endpoints}/sites.go | 2 +- .../{api_endpoints => endpoints}/tags.go | 2 +- .../{api_endpoints => endpoints}/types.go | 2 +- .../{api_endpoints => endpoints}/users.go | 2 +- .../{api_payloads => payloads}/alerting.go | 2 +- .../custom_application.go | 16 +- .../custom_dimension.go | 20 +-- .../{api_payloads => payloads}/device.go | 34 ++-- .../device_label.go | 25 +-- .../{api_payloads => payloads}/interface.go | 41 ++--- .../{api_payloads => payloads}/plan.go | 11 +- .../{api_payloads => payloads}/populator.go | 16 +- .../{api_payloads => payloads}/query.go | 73 +++++---- .../{api_payloads => payloads}/query_test.go | 38 +++-- .../saved_filter.go | 12 +- .../{api_payloads => payloads}/site.go | 16 +- .../{api_payloads => payloads}/tag.go | 3 +- .../{api_payloads => payloads}/tenant.go | 2 +- .../{api_payloads => payloads}/types.go | 9 +- .../{api_payloads => payloads}/types_test.go | 28 ++-- .../{api_payloads => payloads}/user.go | 3 +- kentikapi/internal/resources/alerting.go | 63 ++++++++ .../alerting_test.go | 44 +++-- .../{api_resources => resources}/base.go | 19 +-- .../internal/resources/custom_applications.go | 64 ++++++++ .../custom_applications_test.go | 30 ++-- .../internal/resources/custom_dimensions.go | 119 ++++++++++++++ .../custom_dimensions_test.go | 70 +++++--- kentikapi/internal/resources/device_labels.go | 85 ++++++++++ .../device_labels_test.go | 36 +++-- kentikapi/internal/resources/devices.go | 152 ++++++++++++++++++ .../devices_test.go | 148 ++++++++++------- .../internal/resources/my_kentik_portal.go | 62 +++++++ .../my_kentik_portal_test.go | 51 +++--- kentikapi/internal/resources/plans.go | 31 ++++ .../plans_test.go | 12 +- kentikapi/internal/resources/query.go | 78 +++++++++ .../query_test.go | 85 +++++++--- kentikapi/internal/resources/saved_filters.go | 67 ++++++++ .../saved_filters_test.go | 52 +++--- kentikapi/internal/resources/sites.go | 85 ++++++++++ .../sites_test.go | 36 +++-- .../{api_resources => resources}/tags.go | 33 ++-- .../{api_resources => resources}/users.go | 33 ++-- kentikapi/internal/testutil/http.go | 26 +-- kentikapi/internal/utils/convert.go | 6 +- kentikapi/internal/utils/convert_test.go | 12 +- kentikapi/internal/utils/json_inspector.go | 41 ++--- kentikapi/internal/validation/validate.go | 21 +-- kentikapi/models/custom_application.go | 2 +- kentikapi/models/custom_dimension.go | 2 +- kentikapi/models/device.go | 79 ++++----- kentikapi/models/device_label.go | 2 +- .../models/enum_aggregate_function_type.go | 4 +- kentikapi/models/enum_chart_view_type.go | 4 +- kentikapi/models/enum_dimension_type.go | 4 +- kentikapi/models/enum_fast_data_type.go | 4 +- kentikapi/models/enum_image_type.go | 4 +- kentikapi/models/enum_metric_type.go | 4 +- kentikapi/models/enum_time_format.go | 4 +- kentikapi/models/interface.go | 4 +- kentikapi/models/populator.go | 2 +- kentikapi/models/query_object.go | 10 +- kentikapi/models/setoptional.go | 2 +- kentikapi/models/site.go | 2 +- kentikapi/tags_integration_test.go | 26 +++ kentikapi/users_integration_test.go | 101 +++++++----- 101 files changed, 1923 insertions(+), 1442 deletions(-) delete mode 100644 kentikapi/internal/api_resources/alerting.go delete mode 100644 kentikapi/internal/api_resources/custom_applications.go delete mode 100644 kentikapi/internal/api_resources/custom_dimensions.go delete mode 100644 kentikapi/internal/api_resources/device_labels.go delete mode 100644 kentikapi/internal/api_resources/devices.go delete mode 100644 kentikapi/internal/api_resources/my_kentik_portal.go delete mode 100644 kentikapi/internal/api_resources/plans.go delete mode 100644 kentikapi/internal/api_resources/query.go delete mode 100644 kentikapi/internal/api_resources/saved_filters.go delete mode 100644 kentikapi/internal/api_resources/sites.go rename kentikapi/internal/{api_connection => connection}/rest_client.go (84%) rename kentikapi/internal/{api_connection => connection}/stub_transport.go (96%) rename kentikapi/internal/{api_connection => connection}/transport.go (95%) rename kentikapi/internal/{api_endpoints => endpoints}/alerting.go (91%) rename kentikapi/internal/{api_endpoints => endpoints}/custom_applications.go (94%) rename kentikapi/internal/{api_endpoints => endpoints}/custom_dimensions.go (97%) rename kentikapi/internal/{api_endpoints => endpoints}/device_labels.go (94%) rename kentikapi/internal/{api_endpoints => endpoints}/devices.go (97%) rename kentikapi/internal/{api_endpoints => endpoints}/my_kentik_portal.go (95%) rename kentikapi/internal/{api_endpoints => endpoints}/plans.go (68%) rename kentikapi/internal/{api_endpoints => endpoints}/query.go (90%) rename kentikapi/internal/{api_endpoints => endpoints}/saved_filters.go (90%) rename kentikapi/internal/{api_endpoints => endpoints}/sites.go (93%) rename kentikapi/internal/{api_endpoints => endpoints}/tags.go (87%) rename kentikapi/internal/{api_endpoints => endpoints}/types.go (81%) rename kentikapi/internal/{api_endpoints => endpoints}/users.go (87%) rename kentikapi/internal/{api_payloads => payloads}/alerting.go (99%) rename kentikapi/internal/{api_payloads => payloads}/custom_application.go (93%) rename kentikapi/internal/{api_payloads => payloads}/custom_dimension.go (91%) rename kentikapi/internal/{api_payloads => payloads}/device.go (97%) rename kentikapi/internal/{api_payloads => payloads}/device_label.go (92%) rename kentikapi/internal/{api_payloads => payloads}/interface.go (89%) rename kentikapi/internal/{api_payloads => payloads}/plan.go (94%) rename kentikapi/internal/{api_payloads => payloads}/populator.go (95%) rename kentikapi/internal/{api_payloads => payloads}/query.go (74%) rename kentikapi/internal/{api_payloads => payloads}/query_test.go (74%) rename kentikapi/internal/{api_payloads => payloads}/saved_filter.go (92%) rename kentikapi/internal/{api_payloads => payloads}/site.go (80%) rename kentikapi/internal/{api_payloads => payloads}/tag.go (98%) rename kentikapi/internal/{api_payloads => payloads}/tenant.go (99%) rename kentikapi/internal/{api_payloads => payloads}/types.go (95%) rename kentikapi/internal/{api_payloads => payloads}/types_test.go (59%) rename kentikapi/internal/{api_payloads => payloads}/user.go (96%) create mode 100644 kentikapi/internal/resources/alerting.go rename kentikapi/internal/{api_resources => resources}/alerting_test.go (82%) rename kentikapi/internal/{api_resources => resources}/base.go (88%) create mode 100644 kentikapi/internal/resources/custom_applications.go rename kentikapi/internal/{api_resources => resources}/custom_applications_test.go (88%) create mode 100644 kentikapi/internal/resources/custom_dimensions.go rename kentikapi/internal/{api_resources => resources}/custom_dimensions_test.go (92%) create mode 100644 kentikapi/internal/resources/device_labels.go rename kentikapi/internal/{api_resources => resources}/device_labels_test.go (89%) create mode 100644 kentikapi/internal/resources/devices.go rename kentikapi/internal/{api_resources => resources}/devices_test.go (95%) create mode 100644 kentikapi/internal/resources/my_kentik_portal.go rename kentikapi/internal/{api_resources => resources}/my_kentik_portal_test.go (78%) create mode 100644 kentikapi/internal/resources/plans.go rename kentikapi/internal/{api_resources => resources}/plans_test.go (88%) create mode 100644 kentikapi/internal/resources/query.go rename kentikapi/internal/{api_resources => resources}/query_test.go (89%) create mode 100644 kentikapi/internal/resources/saved_filters.go rename kentikapi/internal/{api_resources => resources}/saved_filters_test.go (84%) create mode 100644 kentikapi/internal/resources/sites.go rename kentikapi/internal/{api_resources => resources}/sites_test.go (84%) rename kentikapi/internal/{api_resources => resources}/tags.go (55%) rename kentikapi/internal/{api_resources => resources}/users.go (55%) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 00d67cb0..2c982f92 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -51,4 +51,4 @@ jobs: - name: Run golangci-lint uses: golangci/golangci-lint-action@v2 with: - version: v1.37 + version: latest diff --git a/.golangci.yml b/.golangci.yml index e83e022e..eec43fc0 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,10 +1,127 @@ +# Configuration reference: https://golangci-lint.run/usage/configuration/ +# Linters reference: https://golangci-lint.run/usage/linters/ run: build-tags: - examples skip-dirs: - apiv6/localhost_apiserver/cloudexport - apiv6/localhost_apiserver/synthetics + issues: max-issues-per-linter: 0 max-same-issues: 0 -# TODO(dfurman): enable more linters + exclude: + # EXC0002 golint: Annoying issue about not having a comment. The rare codebase has such comments + - (comment on exported (method|function|type|const)|should have( a package)? comment|comment should be of the form) + - (struct (of|with)|could be) + exclude-use-default: false + exclude-rules: # exclude linters impossible to exclude via //nolint + - path: ^kentikapi/models/enum_ # these files are generated and shouldn't be edited with //nolint + linters: + - gochecknoglobals + - lll + - gomnd + +# Disabled linters: +# - cyclop - duplicates functionality of gocyclo +# - exhaustivestruct - breaks "Make the zero value useful" proverb, meant to be used only for special cases +# - funlen - only test functions exceeds the line limit of 60 - too strict, these functions are easily readable +# - godox - requires all TODOs to be removed - too strict +# - gomoddirectives - does not allow "replace" directives - too strict +# - goerr113 - following check is too strict: "do not define dynamic errors, use wrapped static errors instead", +# the check cannot be disabled +# - interfacer - deprecated (since v1.38.0) due to: The repository of the linter has been archived by the owner +# - maligned - deprecated (since v1.38.0) due to: The repository of the linter has been archived by the owner +# - nlreturn - leads to using too many line breaks +# - prealloc - from docs: + # XXX: we don't recommend using this linter before doing performance profiling. + # For most programs usage of prealloc will be a premature optimization. +# - scopelint - deprecated (since v1.39.0) due to: The repository of the linter has been deprecated by the owner +# - thelper - enforcing t.Helper() everywhere is too strict +# - wrapcheck - valuable linter which I think needs higher level knowledge on the project to be fixed +# - wsl - leads to using too many line breaks +linters: + enable: + - asciicheck + - bodyclose + - deadcode + - depguard + - dogsled + - dupl + - durationcheck + - errcheck + - errorlint + - exhaustive + - exportloopref + - forbidigo + - forcetypeassert + - gci + - gochecknoglobals + - gochecknoinits + - gocognit + - goconst + - gocritic + - gocyclo + - godot + - gofmt + - gofumpt + - goheader + - goimports + - revive + - gomnd + - gomodguard + - goprintffuncname + - gosec + - gosimple + - govet + - ifshort + - importas + - ineffassign + - lll + - makezero + - misspell + - nakedret + - nestif + - nilerr + - noctx + - nolintlint + - paralleltest + - predeclared + - revive + - rowserrcheck + - sqlclosecheck + - staticcheck + - structcheck + - stylecheck + - testpackage + - tparallel + - typecheck + - unconvert + - unparam + - unused + - varcheck + - wastedassign + - whitespace + +linters-settings: + dupl: + tests: false + errcheck: + check-type-assertions: true + check-blank: true + errorlint: + # Check whether fmt.Errorf uses the %w verb for formatting errors - too strict + errorf: false + gocyclo: + min-complexity: 11 + golint: + min-confidence: 0 + gosec: + tests: false + govet: + enable-all: true + lll: + # lines longer than 127 will be reported, 120 is default + line-length: 127 + nakedret: + max-func-lines: 5 \ No newline at end of file diff --git a/apiv6/kentikapi/client.go b/apiv6/kentikapi/client.go index a8cadce6..64ce5fa1 100644 --- a/apiv6/kentikapi/client.go +++ b/apiv6/kentikapi/client.go @@ -1,3 +1,4 @@ +//nolint:revive,stylecheck // Changing Api to API forces changes in generated files package kentikapi import ( @@ -6,6 +7,7 @@ import ( "github.com/kentik/community_sdk_golang/apiv6/kentikapi/synthetics" ) +//nolint:gosec const ( authAPITokenKey = "X-CH-Auth-API-Token" authEmailKey = "X-CH-Auth-Email" diff --git a/apiv6/kentikapi/client_integration_test.go b/apiv6/kentikapi/client_integration_test.go index ca1ac4c0..4c0029ba 100644 --- a/apiv6/kentikapi/client_integration_test.go +++ b/apiv6/kentikapi/client_integration_test.go @@ -16,6 +16,7 @@ import ( "github.com/stretchr/testify/assert" ) +//nolint:gosec const ( authEmailKey = "X-CH-Auth-Email" authAPITokenKey = "X-CH-Auth-API-Token" @@ -24,7 +25,10 @@ const ( testAgentID = "968" ) +//nolint:errcheck // Conflict with defer Close() (additional info: https://github.com/kisielk/errcheck/issues/55) func TestClient_PatchAgent(t *testing.T) { + t.Parallel() + tests := []struct { name string retryMax *int @@ -160,7 +164,10 @@ func TestClient_PatchAgent(t *testing.T) { }, } for _, tt := range tests { + tt := tt t.Run(tt.name, func(t *testing.T) { + t.Parallel() + // arrange h := newSpyHTTPHandler(t, tt.responses) s := httptest.NewServer(h) @@ -185,6 +192,7 @@ func TestClient_PatchAgent(t *testing.T) { AgentPatch(context.Background(), testAgentID). Body(tt.request). Execute() + defer httpResp.Body.Close() // assert t.Logf("Got result: %v, httpResp: %v, err: %v", result, httpResp, err) @@ -197,7 +205,7 @@ func TestClient_PatchAgent(t *testing.T) { assert.Equal(t, len(h.responses), len(h.requests), "invalid number of requests") for _, r := range h.requests { assert.Equal(t, http.MethodPatch, r.method) - assert.Equal(t, fmt.Sprintf("/synthetics/v202101beta1/agents/%v", testAgentID), r.url_.Path) + assert.Equal(t, fmt.Sprintf("/synthetics/v202101beta1/agents/%v", testAgentID), r.url.Path) assert.Equal(t, dummyAuthEmail, r.header.Get(authEmailKey)) assert.Equal(t, dummyAuthToken, r.header.Get(authAPITokenKey)) assert.Equal(t, tt.expectedRequestBody, unmarshalJSONToIf(t, r.body)) @@ -225,26 +233,34 @@ func newDummyAgent() *synthetics.V202101beta1Agent { status := synthetics.V202101BETA1AGENTSTATUS_WAIT family := synthetics.V202101BETA1IPFAMILY_DUAL agent := &synthetics.V202101beta1Agent{ - Id: stringPtr(testAgentID), - Name: stringPtr("dummy-agent"), - Status: &status, - Alias: stringPtr("probe-4-ams-1"), - Type: stringPtr("global"), - Os: stringPtr("I use Manjaro BTW"), - Ip: stringPtr("95.179.136.58"), - Lat: float64Ptr(52.374031), - Long: float64Ptr(4.88969), - LastAuthed: timePtr(time.Date(2020, time.July, 9, 21, 37, 00, 826*1000000, time.UTC)), - Family: &family, - Asn: int64Ptr(20473), - SiteId: stringPtr("2137"), - Version: stringPtr("0.0.2"), - Challenge: stringPtr("dummy-challenge"), - City: stringPtr("Amsterdam"), - Region: stringPtr("Noord-Holland"), - Country: stringPtr("Netherlands"), - TestIds: &[]string{"13", "133", "1337"}, - LocalIp: stringPtr("10.10.10.10"), + Id: stringPtr(testAgentID), + Name: stringPtr("dummy-agent"), + Status: &status, + Alias: stringPtr("probe-4-ams-1"), + Type: stringPtr("global"), + Os: stringPtr("I use Manjaro BTW"), + Ip: stringPtr("95.179.136.58"), + Lat: float64Ptr(52.374031), + Long: float64Ptr(4.88969), + LastAuthed: timePtr(time.Date(2020, + time.July, + 9, + 21, + 37, + 0, + 826*1000000, + time.UTC, + )), + Family: &family, + Asn: int64Ptr(20473), + SiteId: stringPtr("2137"), + Version: stringPtr("0.0.2"), + Challenge: stringPtr("dummy-challenge"), + City: stringPtr("Amsterdam"), + Region: stringPtr("Noord-Holland"), + Country: stringPtr("Netherlands"), + TestIds: &[]string{"13", "133", "1337"}, + LocalIp: stringPtr("10.10.10.10"), } return agent @@ -336,7 +352,7 @@ func (h *spyHTTPHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) { h.requests = append(h.requests, httpRequest{ method: r.Method, - url_: r.URL, + url: r.URL, header: r.Header, body: string(body), }) @@ -364,7 +380,7 @@ func (h *spyHTTPHandler) response() httpResponse { type httpRequest struct { method string - url_ *url.URL + url *url.URL header http.Header body string } diff --git a/apiv6/kentikapi/httputil/httputil.go b/apiv6/kentikapi/httputil/httputil.go index 0790b27a..e50b6ea8 100644 --- a/apiv6/kentikapi/httputil/httputil.go +++ b/apiv6/kentikapi/httputil/httputil.go @@ -85,6 +85,7 @@ func (cfg *ClientConfig) FillDefaults() { } } +//nolint:gomnd // This is the only place for these numbers to turn up. func defaultHTTPClient() *http.Client { return &http.Client{ Transport: &http.Transport{ diff --git a/apiv6/kentikapi/httputil/httputil_test.go b/apiv6/kentikapi/httputil/httputil_test.go index 9d4caf0e..7e434207 100644 --- a/apiv6/kentikapi/httputil/httputil_test.go +++ b/apiv6/kentikapi/httputil/httputil_test.go @@ -1,4 +1,4 @@ -package httputil +package httputil_test import ( "context" @@ -10,7 +10,7 @@ import ( "time" "github.com/hashicorp/go-retryablehttp" - + "github.com/kentik/community_sdk_golang/apiv6/kentikapi/httputil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -22,15 +22,23 @@ import ( // 4. retryingClient.retryableRoundTripper.retryableClient.httpClient.Do() // 5. retryingClient.retryableRoundTripper.retryableClient.httpClient.httpTransport.RoundTrip() +//nolint:errcheck // https://github.com/kisielk/errcheck/issues/55 +// Closing a response you only read from cannot yield a meaningful error. func TestRetryingClient_Do_ReturnsHTTPTransportError(t *testing.T) { + t.Parallel() + // arrange - c := NewRetryingClient(ClientConfig{}) + c := httputil.NewRetryingClient(httputil.ClientConfig{}) req, err := retryablehttp.NewRequest(http.MethodGet, "https://invalid.url", nil) require.NoError(t, err) // act resp, err := c.Do(req.WithContext(context.Background())) + if err != nil { + return + } + defer resp.Body.Close() // assert t.Logf("Got response: %v, err: %v", resp, err) @@ -40,7 +48,11 @@ func TestRetryingClient_Do_ReturnsHTTPTransportError(t *testing.T) { assert.Equal(t, "no such host", dnsErr.Err) } +//nolint:errcheck // https://github.com/kisielk/errcheck/issues/55 +// Closing a response you only read from cannot yield a meaningful error. func TestRetryingClientWithSpyHTTPTransport_Do(t *testing.T) { + t.Parallel() + const retryMax = 5 tests := []struct { @@ -73,15 +85,17 @@ func TestRetryingClientWithSpyHTTPTransport_Do(t *testing.T) { }, } for _, tt := range tests { + tt := tt t.Run(tt.name, func(t *testing.T) { - // arrange + t.Parallel() + // arrange st := spyTransport{transportError: tt.transportError} - c := NewRetryingClient(ClientConfig{ + c := httputil.NewRetryingClient(httputil.ClientConfig{ HTTPClient: &http.Client{ Transport: &st, }, - RetryCfg: RetryConfig{ + RetryCfg: httputil.RetryConfig{ MaxAttempts: intPtr(retryMax), MinDelay: durationPtr(1 * time.Microsecond), MaxDelay: durationPtr(10 * time.Microsecond), @@ -93,6 +107,10 @@ func TestRetryingClientWithSpyHTTPTransport_Do(t *testing.T) { // act resp, err := c.Do(req.WithContext(context.Background())) + if err != nil { + return + } + defer resp.Body.Close() // assert t.Logf("Got response: %v, err: %v", resp, err) diff --git a/apiv6/localhost_apiserver/main.go b/apiv6/localhost_apiserver/main.go index 8db5f496..a722c632 100644 --- a/apiv6/localhost_apiserver/main.go +++ b/apiv6/localhost_apiserver/main.go @@ -7,7 +7,6 @@ import ( "time" "github.com/gorilla/mux" - cloudexportstub "github.com/kentik/community_sdk_golang/apiv6/localhost_apiserver/cloudexport/go" syntheticsstub "github.com/kentik/community_sdk_golang/apiv6/localhost_apiserver/synthetics/go" ) @@ -15,7 +14,10 @@ import ( func main() { address, cloudexportFilePath, syntheticsFilePath := readAddressStoragePaths() - router := makeRouter(cloudexportstub.NewCloudExportRepo(cloudexportFilePath), syntheticsstub.NewSyntheticsRepo(syntheticsFilePath)) + router := makeRouter( + cloudexportstub.NewCloudExportRepo(cloudexportFilePath), + syntheticsstub.NewSyntheticsRepo(syntheticsFilePath), + ) log.Printf("Server started, address %s", address) log.Fatal(http.ListenAndServe(address, router)) @@ -23,10 +25,20 @@ func main() { func readAddressStoragePaths() (address string, cloudexport string, synthetics string) { flag.StringVar(&address, "addr", ":8080", "Address for the server to listen on") - flag.StringVar(&cloudexport, "cloudexport", "CloudExportStorage.json", "JSON file path for the server to read and write the cloud export data to") - flag.StringVar(&synthetics, "synthetics", "SyntheticsStorage.json", "JSON file path for the server to read and write the synthetics data to") + flag.StringVar( + &cloudexport, + "cloudexport", + "CloudExportStorage.json", + "JSON file path for the server to read and write the cloud export data to", + ) + flag.StringVar( + &synthetics, + "synthetics", + "SyntheticsStorage.json", + "JSON file path for the server to read and write the synthetics data to", + ) flag.Parse() - return + return address, cloudexport, synthetics } func makeRouter(cr *cloudexportstub.CloudExportRepo, sr *syntheticsstub.SyntheticsRepo) *mux.Router { diff --git a/examples/custom_applications_example_test.go b/examples/custom_applications_example_test.go index 6941d013..3ee20525 100644 --- a/examples/custom_applications_example_test.go +++ b/examples/custom_applications_example_test.go @@ -12,6 +12,8 @@ import ( ) func TestCustomApplicationsAPIExample(t *testing.T) { + t.Parallel() + assert := assert.New(t) assert.NoError(runCRUDCustomApplications()) assert.NoError(runGetAllCustomApplications()) diff --git a/examples/demos/retry_demo/main.go b/examples/demos/retry_demo/main.go index 4a2aad67..02f99568 100644 --- a/examples/demos/retry_demo/main.go +++ b/examples/demos/retry_demo/main.go @@ -46,8 +46,8 @@ func showRetryingOnMultipleCodes() error { APIURL: s.URL, RetryCfg: httputil.RetryConfig{ MaxAttempts: intPtr(42), - MinDelay: durationPtr(100 * time.Millisecond), - MaxDelay: durationPtr(10 * time.Second), + MinDelay: durationPtr(1 * time.Second), + MaxDelay: durationPtr(2 * time.Second), RetryableStatusCodes: []int{http.StatusTooManyRequests, http.StatusBadGateway, http.StatusServiceUnavailable}, RetryableMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE"}, }, @@ -62,10 +62,6 @@ func showRetryingOnMultipleCodes() error { return err } -const ( - retryAfterHeaderValue = "2" -) - type spyHTTPHandler struct { // responses to return to the client responses []httpResponse @@ -102,7 +98,7 @@ func (h *spyHTTPHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) { }) rw.Header().Set("Content-Type", "application/json") - rw.Header().Set("Retry-After", retryAfterHeaderValue) + rw.Header().Set("Retry-After", "1") response := h.response() writeResponse(rw, response.statusCode, response.body) } diff --git a/go.mod b/go.mod index e3004e2a..54ddb3d6 100644 --- a/go.mod +++ b/go.mod @@ -4,9 +4,11 @@ go 1.15 require ( github.com/antchfx/jsonquery v1.1.4 + github.com/daixiang0/gci v0.2.9 // indirect github.com/gorilla/mux v1.8.0 github.com/hashicorp/go-retryablehttp v0.7.0 github.com/stretchr/testify v1.7.0 golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4 // indirect golang.org/x/oauth2 v0.0.0-20210817223510-7df4dd6e12ab + mvdan.cc/gofumpt v0.1.1 // indirect ) diff --git a/go.sum b/go.sum index 252b051f..64d8c0e7 100644 --- a/go.sum +++ b/go.sum @@ -43,6 +43,8 @@ github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5P github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/daixiang0/gci v0.2.9 h1:iwJvwQpBZmMg31w+QQ6jsyZ54KEATn6/nfARbBNW294= +github.com/daixiang0/gci v0.2.9/go.mod h1:+4dZ7TISfSmqfAGv59ePaHfNzgGtIkHAhhdKggP1JAc= 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= @@ -89,6 +91,8 @@ github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.1 h1:JFrFEBb2xKufg6XkJsJr+WbKb4FQlURi5RUcBveYu9k= github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.4 h1:L8R9j+yAqZuZjsqh/z+F1NCffTKKLShY6zXTItVIZ8M= +github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= @@ -124,6 +128,7 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rogpeppe/go-internal v1.6.2/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= @@ -132,6 +137,7 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= @@ -172,6 +178,8 @@ golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzB golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.0 h1:8pl+sMODzuvGJkmj2W4kZihvVb5mKm8pB/X44PIQHv8= +golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -198,6 +206,7 @@ golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/ golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4 h1:4nGaVu0QrbjT/AK2PRLuQfQuh6DJve+pELhqTdAj3x0= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -215,6 +224,7 @@ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -240,6 +250,7 @@ golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= @@ -291,6 +302,9 @@ golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roY golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20201118003311-bd56c0adb394/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20210101214203-2dba1e4ea05c h1:dS09fXwOFF9cXBnIzZexIuUBj95U1NyQjkEhkgidDow= +golang.org/x/tools v0.0.0-20210101214203-2dba1e4ea05c/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -374,6 +388,7 @@ google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlba gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= @@ -385,6 +400,8 @@ honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWh honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +mvdan.cc/gofumpt v0.1.1 h1:bi/1aS/5W00E2ny5q65w9SnKpWEF/UIOqDYBILpo9rA= +mvdan.cc/gofumpt v0.1.1/go.mod h1:yXG1r1WqZVKWbVRtBWKWX9+CxGYfA51nSomhM0woR48= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= diff --git a/kentikapi/client.go b/kentikapi/client.go index 19d57f97..383a0b96 100644 --- a/kentikapi/client.go +++ b/kentikapi/client.go @@ -2,8 +2,8 @@ package kentikapi import ( "github.com/kentik/community_sdk_golang/apiv6/kentikapi/httputil" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_resources" + "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/resources" ) // Public constants. @@ -14,19 +14,19 @@ const ( // Client is the root object for manipulating all the Kentik API resources. type Client struct { - Users *api_resources.UsersAPI - Devices *api_resources.DevicesAPI - DeviceLabels *api_resources.DeviceLabelsAPI - Sites *api_resources.SitesAPI - Tags *api_resources.TagsAPI - SavedFilters *api_resources.SavedFiltersAPI - CustomDimensions *api_resources.CustomDimensionsAPI - CustomApplications *api_resources.CustomApplicationsAPI - Query *api_resources.QueryAPI - MyKentikPortal *api_resources.MyKentikPortalAPI - Plans *api_resources.PlansAPI + Users *resources.UsersAPI + Devices *resources.DevicesAPI + DeviceLabels *resources.DeviceLabelsAPI + Sites *resources.SitesAPI + Tags *resources.TagsAPI + SavedFilters *resources.SavedFiltersAPI + CustomDimensions *resources.CustomDimensionsAPI + CustomApplications *resources.CustomApplicationsAPI + Query *resources.QueryAPI + MyKentikPortal *resources.MyKentikPortalAPI + Plans *resources.PlansAPI // Batch - Alerting *api_resources.AlertingAPI + Alerting *resources.AlertingAPI config Config } @@ -45,26 +45,26 @@ func NewClient(c Config) *Client { if c.APIURL == "" { c.APIURL = APIURLUS } - rc := api_connection.NewRestClient(api_connection.RestClientConfig{ + rc := connection.NewRestClient(connection.RestClientConfig{ APIURL: c.APIURL, AuthEmail: c.AuthEmail, AuthToken: c.AuthToken, RetryCfg: c.RetryCfg, }) return &Client{ - Users: api_resources.NewUsersAPI(rc), - Devices: api_resources.NewDevicesAPI(rc), - DeviceLabels: api_resources.NewDeviceLabelsAPI(rc), - Sites: api_resources.NewSitesAPI(rc), - Tags: api_resources.NewTagsAPI(rc), - SavedFilters: api_resources.NewSavedFiltersAPI(rc), - CustomDimensions: api_resources.NewCustomDimensionsAPI(rc), - CustomApplications: api_resources.NewCustomApplicationsAPI(rc), - Query: api_resources.NewQueryAPI(rc), - MyKentikPortal: api_resources.NewMyKentikPortalAPI(rc), - Plans: api_resources.NewPlansAPI(rc), + Users: resources.NewUsersAPI(rc), + Devices: resources.NewDevicesAPI(rc), + DeviceLabels: resources.NewDeviceLabelsAPI(rc), + Sites: resources.NewSitesAPI(rc), + Tags: resources.NewTagsAPI(rc), + SavedFilters: resources.NewSavedFiltersAPI(rc), + CustomDimensions: resources.NewCustomDimensionsAPI(rc), + CustomApplications: resources.NewCustomApplicationsAPI(rc), + Query: resources.NewQueryAPI(rc), + MyKentikPortal: resources.NewMyKentikPortalAPI(rc), + Plans: resources.NewPlansAPI(rc), // Batch - Alerting: api_resources.NewAlertingAPI(rc), + Alerting: resources.NewAlertingAPI(rc), config: c, } } diff --git a/kentikapi/internal/api_resources/alerting.go b/kentikapi/internal/api_resources/alerting.go deleted file mode 100644 index ed64dca1..00000000 --- a/kentikapi/internal/api_resources/alerting.go +++ /dev/null @@ -1,62 +0,0 @@ -package api_resources - -import ( - "context" - "errors" - - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_endpoints" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" - "github.com/kentik/community_sdk_golang/kentikapi/models" -) - -type AlertingAPI struct { - BaseAPI -} - -// NewAlertingAPI is constructor -func NewAlertingAPI(transport api_connection.Transport) *AlertingAPI { - return &AlertingAPI{ - BaseAPI{Transport: transport}, - } -} - -func (a *AlertingAPI) CreateManualMitigation(ctx context.Context, mm models.ManualMitigation) error { - payload := api_payloads.ManualMitigationToPayload(mm) - var response api_payloads.CreateManualMitigationResponse - - if err := a.PostAndValidate(ctx, api_endpoints.ManualMitigationPath, payload, &response); err != nil { - return err - } - - if response.Response.Result != "OK" { - return errors.New("creating Manual Mitigation failed") - } - - return nil -} - -func (a *AlertingAPI) GetActiveAlerts(ctx context.Context, params models.AlertsQueryParams) ([]models.Alarm, error) { - var response api_payloads.GetActiveAlertsResponse - - path := api_endpoints.GetActiveAlertsPath(params.StartTime, params.EndTime, params.FilterBy, params.FilterVal, - params.ShowMitigations, params.ShowAlarms, params.ShowMatches, params.LearningMode) - - if err := a.GetAndValidate(ctx, path, &response); err != nil { - return nil, err - } - - return response.ToAlarms(), nil -} - -func (a *AlertingAPI) GetAlertsHistory(ctx context.Context, params models.AlertsQueryParams) ([]models.HistoricalAlert, error) { - var response api_payloads.GetHistoricalAlertsResponse - path := api_endpoints.GetAlertsHistoryPath(params.StartTime, params.EndTime, params.FilterBy, params.FilterVal, - params.SortOrder, params.ShowMitigations, params.ShowAlarms, params.ShowMatches, params.LearningMode) - - if err := a.GetAndValidate(ctx, path, &response); err != nil { - return nil, err - } - - return response.ToHistoricalAlerts(), nil -} diff --git a/kentikapi/internal/api_resources/custom_applications.go b/kentikapi/internal/api_resources/custom_applications.go deleted file mode 100644 index 486a55be..00000000 --- a/kentikapi/internal/api_resources/custom_applications.go +++ /dev/null @@ -1,62 +0,0 @@ -package api_resources - -import ( - "context" - - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_endpoints" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" - "github.com/kentik/community_sdk_golang/kentikapi/models" -) - -type CustomApplicationsAPI struct { - BaseAPI -} - -// NewCustomApplicationsAPI is constructor -func NewCustomApplicationsAPI(transport api_connection.Transport) *CustomApplicationsAPI { - return &CustomApplicationsAPI{ - BaseAPI{Transport: transport}, - } -} - -// GetAll custom applications -func (a *CustomApplicationsAPI) GetAll(ctx context.Context) ([]models.CustomApplication, error) { - var response api_payloads.GetAllCustomApplicationsResponse - if err := a.GetAndValidate(ctx, api_endpoints.GetAllCustomApplications(), &response); err != nil { - return []models.CustomApplication{}, err - } - - return response.ToCustomApplications() -} - -// Create new custom application -func (a *CustomApplicationsAPI) Create(ctx context.Context, customApplication models.CustomApplication) (*models.CustomApplication, error) { - payload := api_payloads.CustomApplicationToPayload(customApplication) - request := api_payloads.CreateCustomApplicationRequest(payload) - var response api_payloads.CreateCustomApplicationResponse - if err := a.PostAndValidate(ctx, api_endpoints.CreateCustomApplication(), request, &response); err != nil { - return nil, err - } - - result, err := response.ToCustomApplication() - return &result, err -} - -// Update custom application -func (a *CustomApplicationsAPI) Update(ctx context.Context, customApplication models.CustomApplication) (*models.CustomApplication, error) { - payload := api_payloads.CustomApplicationToPayload(customApplication) - request := api_payloads.UpdateCustomApplicationRequest(payload) - var response api_payloads.UpdateCustomApplicationResponse - if err := a.UpdateAndValidate(ctx, api_endpoints.UpdateCustomApplication(customApplication.ID), request, &response); err != nil { - return nil, err - } - - result, err := response.ToCustomApplication() - return &result, err -} - -// Delete custom application -func (a *CustomApplicationsAPI) Delete(ctx context.Context, id models.ID) error { - return a.DeleteAndValidate(ctx, api_endpoints.DeleteCustomApplication(id), nil) -} diff --git a/kentikapi/internal/api_resources/custom_dimensions.go b/kentikapi/internal/api_resources/custom_dimensions.go deleted file mode 100644 index c26651f6..00000000 --- a/kentikapi/internal/api_resources/custom_dimensions.go +++ /dev/null @@ -1,114 +0,0 @@ -package api_resources - -import ( - "context" - - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_endpoints" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" - "github.com/kentik/community_sdk_golang/kentikapi/models" -) - -type CustomDimensionsAPI struct { - BaseAPI - Populators *populatorsAPI -} - -// NewCustomDimensionsAPI is constructor -func NewCustomDimensionsAPI(transport api_connection.Transport) *CustomDimensionsAPI { - return &CustomDimensionsAPI{ - BaseAPI{Transport: transport}, - &populatorsAPI{BaseAPI{Transport: transport}}, - } -} - -// GetAll custom dimensions -func (a *CustomDimensionsAPI) GetAll(ctx context.Context) ([]models.CustomDimension, error) { - var response api_payloads.GetAllCustomDimensionsResponse - if err := a.GetAndValidate(ctx, api_endpoints.GetAllCustomDimensions(), &response); err != nil { - return []models.CustomDimension{}, err - } - - return response.ToCustomDimensions(), nil -} - -// Get custom dimension with given ID -func (a *CustomDimensionsAPI) Get(ctx context.Context, id models.ID) (*models.CustomDimension, error) { - var response api_payloads.GetCustomDimensionResponse - if err := a.GetAndValidate(ctx, api_endpoints.GetCustomDimension(id), &response); err != nil { - return nil, err - } - - result := response.ToCustomDimension() - return &result, nil -} - -// Create new custom dimension -func (a *CustomDimensionsAPI) Create(ctx context.Context, customDimension models.CustomDimension) (*models.CustomDimension, error) { - payload := api_payloads.CustomDimensionToPayload(customDimension) - - request := api_payloads.CreateCustomDimensionRequest(payload) - var response api_payloads.CreateCustomDimensionResponse - if err := a.PostAndValidate(ctx, api_endpoints.CreateCustomDimension(), request, &response); err != nil { - return nil, err - } - - result := response.ToCustomDimension() - return &result, nil -} - -// Update custom dimension -func (a *CustomDimensionsAPI) Update(ctx context.Context, customDimension models.CustomDimension) (*models.CustomDimension, error) { - payload := api_payloads.CustomDimensionToPayload(customDimension) - - request := api_payloads.UpdateCustomDimensionRequest(payload) - var response api_payloads.UpdateCustomDimensionResponse - if err := a.UpdateAndValidate(ctx, api_endpoints.UpdateCustomDimension(customDimension.ID), request, &response); err != nil { - return nil, err - } - - result := response.ToCustomDimension() - return &result, nil -} - -// Delete custom dimension -func (a *CustomDimensionsAPI) Delete(ctx context.Context, id models.ID) error { - return a.DeleteAndValidate(ctx, api_endpoints.DeleteCustomDimension(id), nil) -} - -type populatorsAPI struct { - BaseAPI -} - -// Create new populator -func (a *populatorsAPI) Create(ctx context.Context, populator models.Populator) (*models.Populator, error) { - payload := api_payloads.PopulatorToPayload(populator) - - request := api_payloads.CreatePopulatorRequest{Payload: payload} - var response api_payloads.CreatePopulatorResponse - if err := a.PostAndValidate(ctx, api_endpoints.CreatePopulator(populator.DimensionID), request, &response); err != nil { - return nil, err - } - - result := response.ToPopulator() - return &result, nil -} - -// Update populator -func (a *populatorsAPI) Update(ctx context.Context, populator models.Populator) (*models.Populator, error) { - payload := api_payloads.PopulatorToPayload(populator) - - request := api_payloads.UpdatePopulatorRequest{Payload: payload} - var response api_payloads.UpdatePopulatorResponse - if err := a.UpdateAndValidate(ctx, api_endpoints.UpdatePopulator(populator.DimensionID, populator.ID), request, &response); err != nil { - return nil, err - } - - result := response.ToPopulator() - return &result, nil -} - -// Delete populator -func (a *populatorsAPI) Delete(ctx context.Context, dimensionID, populatorID models.ID) error { - return a.DeleteAndValidate(ctx, api_endpoints.DeletePopulator(dimensionID, populatorID), nil) -} diff --git a/kentikapi/internal/api_resources/device_labels.go b/kentikapi/internal/api_resources/device_labels.go deleted file mode 100644 index 14d692c0..00000000 --- a/kentikapi/internal/api_resources/device_labels.go +++ /dev/null @@ -1,85 +0,0 @@ -package api_resources - -import ( - "context" - "fmt" - - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_endpoints" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" - "github.com/kentik/community_sdk_golang/kentikapi/models" -) - -type DeviceLabelsAPI struct { - BaseAPI -} - -// NewDeviceLabelsAPIis constructor -func NewDeviceLabelsAPI(transport api_connection.Transport) *DeviceLabelsAPI { - return &DeviceLabelsAPI{ - BaseAPI{Transport: transport}, - } -} - -// GetAll labels -func (a *DeviceLabelsAPI) GetAll(ctx context.Context) ([]models.DeviceLabel, error) { - var response api_payloads.GetAllDeviceLabelsResponse - if err := a.GetAndValidate(ctx, api_endpoints.GetAllLabels(), &response); err != nil { - return []models.DeviceLabel{}, err - } - - return response.ToDeviceLabels() -} - -// Get label with given ID -func (a *DeviceLabelsAPI) Get(ctx context.Context, id models.ID) (*models.DeviceLabel, error) { - var response api_payloads.GetDeviceLabelResponse - if err := a.GetAndValidate(ctx, api_endpoints.GetLabel(id), &response); err != nil { - return nil, err - } - - device, err := response.ToDeviceLabel() - return &device, err -} - -// Create new label -func (a *DeviceLabelsAPI) Create(ctx context.Context, label models.DeviceLabel) (*models.DeviceLabel, error) { - payload := api_payloads.DeviceLabelToPayload(label) - - request := api_payloads.CreateDeviceLabelRequest(payload) - var response api_payloads.CreateDeviceLabelResponse - if err := a.PostAndValidate(ctx, api_endpoints.CreateLabel(), request, &response); err != nil { - return nil, err - } - - result, err := response.ToDeviceLabel() - return &result, err -} - -// Update label -func (a *DeviceLabelsAPI) Update(ctx context.Context, label models.DeviceLabel) (*models.DeviceLabel, error) { - payload := api_payloads.DeviceLabelToPayload(label) - - request := api_payloads.UpdateDeviceLabelRequest(payload) - var response api_payloads.UpdateDeviceLabelResponse - if err := a.UpdateAndValidate(ctx, api_endpoints.UpdateLabel(label.ID), request, &response); err != nil { - return nil, err - } - - result, err := response.ToDeviceLabel() - return &result, err -} - -// Delete label -func (a *DeviceLabelsAPI) Delete(ctx context.Context, id models.ID) error { - var response api_payloads.DeleteDeviceLabelResponse - if err := a.DeleteAndValidate(ctx, api_endpoints.DeleteLabel(id), &response); err != nil { - return err - } - - if !response.Success { - return fmt.Errorf("DeviceLabelsAPI.Delete: API returned success=false for id=%v", id) - } - - return nil -} diff --git a/kentikapi/internal/api_resources/devices.go b/kentikapi/internal/api_resources/devices.go deleted file mode 100644 index bb533689..00000000 --- a/kentikapi/internal/api_resources/devices.go +++ /dev/null @@ -1,152 +0,0 @@ -package api_resources - -import ( - "context" - - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_endpoints" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" - "github.com/kentik/community_sdk_golang/kentikapi/models" -) - -type DevicesAPI struct { - BaseAPI - Interfaces *interfacesAPI -} - -// NewDevicesAPI is constructor -func NewDevicesAPI(transport api_connection.Transport) *DevicesAPI { - return &DevicesAPI{ - BaseAPI{Transport: transport}, - &interfacesAPI{BaseAPI{Transport: transport}}, - } -} - -// GetAll devices -func (a *DevicesAPI) GetAll(ctx context.Context) ([]models.Device, error) { - var response api_payloads.GetAllDevicesResponse - if err := a.GetAndValidate(ctx, api_endpoints.DevicesPath, &response); err != nil { - return []models.Device{}, err - } - - return response.ToDevices() -} - -// Get device with given ID -func (a *DevicesAPI) Get(ctx context.Context, id models.ID) (*models.Device, error) { - var response api_payloads.GetDeviceResponse - if err := a.GetAndValidate(ctx, api_endpoints.GetDevice(id), &response); err != nil { - return nil, err - } - - device, err := response.ToDevice() - return &device, err -} - -// Create new device -func (a *DevicesAPI) Create(ctx context.Context, device models.Device) (*models.Device, error) { - request := api_payloads.CreateDeviceRequest{Payload: api_payloads.DeviceToPayload(device)} - var response api_payloads.CreateDeviceResponse - if err := a.PostAndValidate(ctx, api_endpoints.DevicePath, request, &response); err != nil { - return nil, err - } - - result, err := response.ToDevice() - return &result, err -} - -// Update device -func (a *DevicesAPI) Update(ctx context.Context, device models.Device) (*models.Device, error) { - request := api_payloads.UpdateDeviceRequest{Payload: api_payloads.DeviceToPayload(device)} - var response api_payloads.UpdateDeviceResponse - if err := a.UpdateAndValidate(ctx, api_endpoints.UpdateDevice(device.ID), request, &response); err != nil { - return nil, err - } - - result, err := response.ToDevice() - return &result, err -} - -// Delete device -// Note: KentikAPI requires sending delete request twice to actually delete the device. -// This is a safety measure preventing deletion by mistake. -func (a *DevicesAPI) Delete(ctx context.Context, id models.ID) error { - return a.DeleteAndValidate(ctx, api_endpoints.GetDevice(id), nil) -} - -// ApplyLabels assigns labels to given device -func (a *DevicesAPI) ApplyLabels(ctx context.Context, deviceID models.ID, labels []models.ID) (models.AppliedLabels, error) { - payload := api_payloads.LabelIDsToPayload(labels) - - request := api_payloads.ApplyLabelsRequest{Labels: payload} - var response api_payloads.ApplyLabelsResponse - if err := a.UpdateAndValidate(ctx, api_endpoints.ApplyDeviceLabels(deviceID), request, &response); err != nil { - return models.AppliedLabels{}, err - } - - return response.ToAppliedLabels() -} - -type interfacesAPI struct { - BaseAPI -} - -// GetAll interfaces of given device -func (a *interfacesAPI) GetAll(ctx context.Context, deviceID models.ID) ([]models.Interface, error) { - var response api_payloads.GetAllInterfacesResponse - if err := a.GetAndValidate(ctx, api_endpoints.GetAllInterfaces(deviceID), &response); err != nil { - return nil, err - } - - return response.ToInterfaces() -} - -// Get interface of given device with given ID -func (a *interfacesAPI) Get(ctx context.Context, deviceID, interfaceID models.ID) (*models.Interface, error) { - var response api_payloads.GetInterfaceResponse - if err := a.GetAndValidate(ctx, api_endpoints.GetInterface(deviceID, interfaceID), &response); err != nil { - return nil, err - } - - intf, err := response.ToInterface() - return &intf, err -} - -// Create new interface under given device -func (a *interfacesAPI) Create(ctx context.Context, intf models.Interface) (*models.Interface, error) { - payload, err := api_payloads.InterfaceToPayload(intf) - if err != nil { - return nil, err - } - - request := api_payloads.CreateInterfaceRequest(payload) - var response api_payloads.CreateInterfaceResponse - if err := a.PostAndValidate(ctx, api_endpoints.CreateInterface(intf.DeviceID), request, &response); err != nil { - return nil, err - } - - result, err := response.ToInterface() - return &result, err -} - -// Delete interface -func (a *interfacesAPI) Delete(ctx context.Context, deviceID, interfaceID models.ID) error { - return a.DeleteAndValidate(ctx, api_endpoints.DeleteInterface(deviceID, interfaceID), nil) -} - -// Update interface -func (a *interfacesAPI) Update(ctx context.Context, intf models.Interface) (*models.Interface, error) { - payload, err := api_payloads.InterfaceToPayload(intf) - if err != nil { - return nil, err - } - - request := api_payloads.UpdateInterfaceRequest(payload) - var response api_payloads.UpdateInterfaceResponse - if err := a.UpdateAndValidate(ctx, api_endpoints.UpdateInterface(intf.DeviceID, intf.ID), request, &response); err != nil { - return nil, err - } - - result, err := response.ToInterface() - return &result, err -} diff --git a/kentikapi/internal/api_resources/my_kentik_portal.go b/kentikapi/internal/api_resources/my_kentik_portal.go deleted file mode 100644 index 8d64aac3..00000000 --- a/kentikapi/internal/api_resources/my_kentik_portal.go +++ /dev/null @@ -1,60 +0,0 @@ -package api_resources - -import ( - "context" - - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_endpoints" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" - "github.com/kentik/community_sdk_golang/kentikapi/models" -) - -type MyKentikPortalAPI struct { - BaseAPI -} - -func NewMyKentikPortalAPI(transport api_connection.Transport) *MyKentikPortalAPI { - return &MyKentikPortalAPI{BaseAPI{Transport: transport}} -} - -// GetAll lists all tenants. -func (a *MyKentikPortalAPI) GetAll(ctx context.Context) ([]models.Tenant, error) { - var response api_payloads.GetAllTenantsResponse - if err := a.GetAndValidate(ctx, api_endpoints.TenantsPath, &response); err != nil { - return []models.Tenant{}, err - } - - return response.ToTenants() -} - -// Get Tenant Info -func (a *MyKentikPortalAPI) Get(ctx context.Context, tenantID models.ID) (*models.Tenant, error) { - var response api_payloads.TenantPayload - if err := a.GetAndValidate(ctx, api_endpoints.GetTenantPath(tenantID), &response); err != nil { - return nil, err - } - tenant, err := response.ToTenant() - return &tenant, err -} - -func (a *MyKentikPortalAPI) CreateTenantUser(ctx context.Context, tenantID models.ID, userEmail string) (*models.TenantUser, error) { - request := api_payloads.CreateTenantUserRequest{ - User: api_payloads.CreateTenantUserPayload{ - Email: userEmail, - }} - var response api_payloads.TenantUserPayload - if err := a.PostAndValidate(ctx, api_endpoints.CreateTenantUserPath(tenantID), request, &response); err != nil { - return nil, err - } - - result, err := response.ToTenantUser() - return &result, err -} - -func (a *MyKentikPortalAPI) DeleteTenantUser(ctx context.Context, tenantID models.ID, userID models.ID) error { - if err := a.DeleteAndValidate(ctx, api_endpoints.DeleteTenantUserPath(tenantID, userID), nil); err != nil { - return err - } - - return nil -} diff --git a/kentikapi/internal/api_resources/plans.go b/kentikapi/internal/api_resources/plans.go deleted file mode 100644 index 600de1bc..00000000 --- a/kentikapi/internal/api_resources/plans.go +++ /dev/null @@ -1,31 +0,0 @@ -package api_resources - -import ( - "context" - - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_endpoints" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" - "github.com/kentik/community_sdk_golang/kentikapi/models" -) - -type PlansAPI struct { - BaseAPI -} - -// NewPlansAPI is constructor -func NewPlansAPI(transport api_connection.Transport) *PlansAPI { - return &PlansAPI{ - BaseAPI{Transport: transport}, - } -} - -// GetAll plans -func (a *PlansAPI) GetAll(ctx context.Context) ([]models.Plan, error) { - var response api_payloads.GetAllPlansResponse - if err := a.GetAndValidate(ctx, api_endpoints.GetAllPlans(), &response); err != nil { - return []models.Plan{}, err - } - - return response.ToPlans() -} diff --git a/kentikapi/internal/api_resources/query.go b/kentikapi/internal/api_resources/query.go deleted file mode 100644 index 14d4327f..00000000 --- a/kentikapi/internal/api_resources/query.go +++ /dev/null @@ -1,78 +0,0 @@ -package api_resources - -import ( - "context" - - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_endpoints" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" - "github.com/kentik/community_sdk_golang/kentikapi/models" -) - -type QueryAPI struct { - BaseAPI -} - -// NewQueryAPI is constructor -func NewQueryAPI(transport api_connection.Transport) *QueryAPI { - return &QueryAPI{ - BaseAPI{Transport: transport}, - } -} - -// SQL query -func (a *QueryAPI) SQL(ctx context.Context, sql string) (models.QuerySQLResult, error) { - payload := api_payloads.QuerySQLRequest{Query: sql} - - var response api_payloads.QuerySQLResponse - if err := a.PostAndValidate(ctx, api_endpoints.QuerySQL(), payload, &response); err != nil { - return models.QuerySQLResult{}, err - } - - return response.ToQuerySQLResult(), nil -} - -// Data query -func (a *QueryAPI) Data(ctx context.Context, query models.QueryObject) (models.QueryDataResult, error) { - payload, err := api_payloads.QueryObjectToPayload(query) - if err != nil { - return models.QueryDataResult{}, err - } - - var response api_payloads.QueryDataResponse - if err := a.PostAndValidate(ctx, api_endpoints.QueryData(), payload, &response); err != nil { - return models.QueryDataResult{}, err - } - - return response.ToQueryDataResult(), nil -} - -// Chart query -func (a *QueryAPI) Chart(ctx context.Context, query models.QueryObject) (models.QueryChartResult, error) { - payload, err := api_payloads.QueryObjectToPayload(query) - if err != nil { - return models.QueryChartResult{}, err - } - - var response api_payloads.QueryChartResponse - if err := a.PostAndValidate(ctx, api_endpoints.QueryChart(), payload, &response); err != nil { - return models.QueryChartResult{}, err - } - - return response.ToQueryChartResult() -} - -// URL query -func (a *QueryAPI) URL(ctx context.Context, query models.QueryObject) (models.QueryURLResult, error) { - payload, err := api_payloads.QueryObjectToPayload(query) - if err != nil { - return models.QueryURLResult{}, err - } - - var response api_payloads.QueryURLResponse - if err := a.PostAndValidate(ctx, api_endpoints.QueryURL(), payload, &response); err != nil { - return models.QueryURLResult{}, err - } - - return response.ToQueryURLResult(), nil -} diff --git a/kentikapi/internal/api_resources/saved_filters.go b/kentikapi/internal/api_resources/saved_filters.go deleted file mode 100644 index 4e6842ab..00000000 --- a/kentikapi/internal/api_resources/saved_filters.go +++ /dev/null @@ -1,67 +0,0 @@ -package api_resources - -import ( - "context" - - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_endpoints" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" - "github.com/kentik/community_sdk_golang/kentikapi/models" -) - -type SavedFiltersAPI struct { - BaseAPI -} - -func NewSavedFiltersAPI(transport api_connection.Transport) *SavedFiltersAPI { - return &SavedFiltersAPI{BaseAPI{Transport: transport}} -} - -func (a *SavedFiltersAPI) GetAll(ctx context.Context) ([]models.SavedFilter, error) { - var response api_payloads.GetAllSavedFilterResponse - if err := a.GetAndValidate(ctx, api_endpoints.SavedFiltersPath, &response); err != nil { - return nil, err - } - - return response.ToSavedFilters() -} - -func (a *SavedFiltersAPI) Get(ctx context.Context, filterID models.ID) (*models.SavedFilter, error) { - var response api_payloads.GetSavedFilterResponse - err := a.GetAndValidate(ctx, api_endpoints.GetSavedFilter(filterID), &response) - if err != nil { - return nil, err - } - - savedFilter, err := response.ToSavedFilter() - - return &savedFilter, err -} - -func (a *SavedFiltersAPI) Create(ctx context.Context, savedFilter models.SavedFilter) (*models.SavedFilter, error) { - payload := api_payloads.SavedFilterToCreatePayload(savedFilter) - - var response api_payloads.CreateSavedFilterResponse - if err := a.PostAndValidate(ctx, api_endpoints.SavedFilterPath, payload, &response); err != nil { - return nil, err - } - - result, err := response.ToSavedFilter() - return &result, err -} - -func (a *SavedFiltersAPI) Update(ctx context.Context, savedFilter models.SavedFilter) (*models.SavedFilter, error) { - payload := api_payloads.SavedFilterToUpdatePayload(savedFilter) - - var response api_payloads.UpdateSavedFilterResponse - if err := a.UpdateAndValidate(ctx, api_endpoints.GetSavedFilter(savedFilter.ID), payload, &response); err != nil { - return nil, err - } - - result, err := response.ToSavedFilter() - return &result, err -} - -func (a *SavedFiltersAPI) Detete(ctx context.Context, id models.ID) error { - return a.DeleteAndValidate(ctx, api_endpoints.GetSavedFilter(id), nil) -} diff --git a/kentikapi/internal/api_resources/sites.go b/kentikapi/internal/api_resources/sites.go deleted file mode 100644 index 431e1375..00000000 --- a/kentikapi/internal/api_resources/sites.go +++ /dev/null @@ -1,85 +0,0 @@ -package api_resources - -import ( - "context" - - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_endpoints" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" - "github.com/kentik/community_sdk_golang/kentikapi/models" -) - -type SitesAPI struct { - BaseAPI -} - -// NewSitesAPI is constructor -func NewSitesAPI(transport api_connection.Transport) *SitesAPI { - return &SitesAPI{ - BaseAPI{Transport: transport}, - } -} - -// GetAll sites -func (a *SitesAPI) GetAll(ctx context.Context) ([]models.Site, error) { - var response api_payloads.GetAllSitesResponse - if err := a.GetAndValidate(ctx, api_endpoints.GetAllSites(), &response); err != nil { - return []models.Site{}, err - } - - return response.ToSites() -} - -// Get site with given ID -func (a *SitesAPI) Get(ctx context.Context, id models.ID) (*models.Site, error) { - var response api_payloads.GetSiteResponse - if err := a.GetAndValidate(ctx, api_endpoints.GetSite(id), &response); err != nil { - return nil, err - } - - site, err := response.ToSite() - return &site, err -} - -// Create new site -func (a *SitesAPI) Create(ctx context.Context, site models.Site) (*models.Site, error) { - payload, err := api_payloads.SiteToPayload(site) - if err != nil { - return nil, err - } - - request := api_payloads.CreateSiteRequest{Payload: payload} - var response api_payloads.CreateSiteResponse - if err := a.PostAndValidate(ctx, api_endpoints.CreateSite(), request, &response); err != nil { - return nil, err - } - - result, err := response.ToSite() - return &result, err -} - -// Update site -func (a *SitesAPI) Update(ctx context.Context, site models.Site) (*models.Site, error) { - payload, err := api_payloads.SiteToPayload(site) - if err != nil { - return nil, err - } - - request := api_payloads.UpdateSiteRequest{Payload: payload} - var response api_payloads.UpdateSiteResponse - if err := a.UpdateAndValidate(ctx, api_endpoints.UpdateSite(site.ID), request, &response); err != nil { - return nil, err - } - - result, err := response.ToSite() - return &result, err -} - -// Delete site -func (a *SitesAPI) Delete(ctx context.Context, id models.ID) error { - if err := a.DeleteAndValidate(ctx, api_endpoints.DeleteSite(id), nil); err != nil { - return err - } - - return nil -} diff --git a/kentikapi/internal/api_connection/rest_client.go b/kentikapi/internal/connection/rest_client.go similarity index 84% rename from kentikapi/internal/api_connection/rest_client.go rename to kentikapi/internal/connection/rest_client.go index 12ac2362..999050ee 100644 --- a/kentikapi/internal/api_connection/rest_client.go +++ b/kentikapi/internal/connection/rest_client.go @@ -1,22 +1,24 @@ -package api_connection +package connection import ( "bytes" "context" "encoding/json" "fmt" - "github.com/hashicorp/go-retryablehttp" - "github.com/kentik/community_sdk_golang/apiv6/kentikapi/httputil" "io/ioutil" "net/http" + + "github.com/hashicorp/go-retryablehttp" + "github.com/kentik/community_sdk_golang/apiv6/kentikapi/httputil" ) +//nolint:gosec const ( authEmailKey = "X-CH-Auth-Email" authAPITokenKey = "X-CH-Auth-API-Token" ) -type restClient struct { +type RestClient struct { config RestClientConfig httpClient *retryablehttp.Client } @@ -28,9 +30,9 @@ type RestClientConfig struct { RetryCfg httputil.RetryConfig } -func NewRestClient(c RestClientConfig) *restClient { - return &restClient{ - config: c, +func NewRestClient(c RestClientConfig) *RestClient { + return &RestClient{ + config: c, httpClient: httputil. NewRetryingClient( httputil.ClientConfig{ @@ -42,7 +44,7 @@ func NewRestClient(c RestClientConfig) *restClient { } // Get sends GET request to the API and returns raw response body. -func (c *restClient) Get(ctx context.Context, path string) (responseBody json.RawMessage, err error) { +func (c *RestClient) Get(ctx context.Context, path string) (responseBody json.RawMessage, err error) { request, err := c.newRequest(ctx, http.MethodGet, path, json.RawMessage{}) if err != nil { return nil, fmt.Errorf("new request: %v", err) @@ -68,8 +70,9 @@ func (c *restClient) Get(ctx context.Context, path string) (responseBody json.Ra return body, errorFromResponseStatus(response, string(body)) } -// Post sends POST request to the API and returns raw response body -func (c *restClient) Post(ctx context.Context, path string, payload json.RawMessage) (responseBody json.RawMessage, err error) { +// Post sends POST request to the API and returns raw response body. +func (c *RestClient) Post(ctx context.Context, + path string, payload json.RawMessage) (responseBody json.RawMessage, err error) { request, err := c.newRequest(ctx, http.MethodPost, path, payload) if err != nil { return nil, fmt.Errorf("new request: %v", err) @@ -94,8 +97,9 @@ func (c *restClient) Post(ctx context.Context, path string, payload json.RawMess return body, errorFromResponseStatus(response, string(body)) } -// Put sends PUT request to the API and returns raw response body -func (c *restClient) Put(ctx context.Context, path string, payload json.RawMessage) (responseBody json.RawMessage, err error) { +// Put sends PUT request to the API and returns raw response body. +func (c *RestClient) Put(ctx context.Context, + path string, payload json.RawMessage) (responseBody json.RawMessage, err error) { request, err := c.newRequest(ctx, http.MethodPut, path, payload) if err != nil { return nil, fmt.Errorf("new request: %v", err) @@ -120,8 +124,8 @@ func (c *restClient) Put(ctx context.Context, path string, payload json.RawMessa return body, errorFromResponseStatus(response, string(body)) } -// Delete sends DELETE request to the API and returns raw response body -func (c *restClient) Delete(ctx context.Context, path string) (responseBody json.RawMessage, err error) { +// Delete sends DELETE request to the API and returns raw response body. +func (c *RestClient) Delete(ctx context.Context, path string) (responseBody json.RawMessage, err error) { request, err := c.newRequest(ctx, http.MethodDelete, path, json.RawMessage{}) if err != nil { return nil, fmt.Errorf("new request: %v", err) @@ -155,7 +159,8 @@ func errorFromResponseStatus(r *http.Response, responseBody string) error { return nil } -func (c *restClient) newRequest(ctx context.Context, method string, path string, payload json.RawMessage) (*retryablehttp.Request, error) { +func (c *RestClient) newRequest(ctx context.Context, method string, + path string, payload json.RawMessage) (*retryablehttp.Request, error) { request, err := http.NewRequestWithContext(ctx, method, c.makeFullURL(path), bytes.NewReader(payload)) if err != nil { return nil, err @@ -168,6 +173,6 @@ func (c *restClient) newRequest(ctx context.Context, method string, path string, return retryablehttp.FromRequest(request) } -func (c *restClient) makeFullURL(path string) string { +func (c *RestClient) makeFullURL(path string) string { return c.config.APIURL + path } diff --git a/kentikapi/internal/api_connection/stub_transport.go b/kentikapi/internal/connection/stub_transport.go similarity index 96% rename from kentikapi/internal/api_connection/stub_transport.go rename to kentikapi/internal/connection/stub_transport.go index 1848103e..a4b87aaf 100644 --- a/kentikapi/internal/api_connection/stub_transport.go +++ b/kentikapi/internal/connection/stub_transport.go @@ -1,4 +1,4 @@ -package api_connection +package connection import ( "context" @@ -6,7 +6,7 @@ import ( "net/http" ) -// StubTransport provides Transport interface with preconfigured ResponseBody +// StubTransport provides Transport interface with preconfigured ResponseBody. type StubTransport struct { ResponseBody string diff --git a/kentikapi/internal/api_connection/transport.go b/kentikapi/internal/connection/transport.go similarity index 95% rename from kentikapi/internal/api_connection/transport.go rename to kentikapi/internal/connection/transport.go index 936c9df4..fcfc90a4 100644 --- a/kentikapi/internal/api_connection/transport.go +++ b/kentikapi/internal/connection/transport.go @@ -1,4 +1,4 @@ -package api_connection +package connection import ( "context" diff --git a/kentikapi/internal/api_endpoints/alerting.go b/kentikapi/internal/endpoints/alerting.go similarity index 91% rename from kentikapi/internal/api_endpoints/alerting.go rename to kentikapi/internal/endpoints/alerting.go index 3de6a7d4..7e467d69 100644 --- a/kentikapi/internal/api_endpoints/alerting.go +++ b/kentikapi/internal/endpoints/alerting.go @@ -1,4 +1,4 @@ -package api_endpoints +package endpoints import ( "fmt" @@ -12,7 +12,9 @@ const ( AlertsHistoryPath = "/alerts-active/alerts-history" ) -func GetActiveAlertsPath(startTime *time.Time, endTime *time.Time, filterBy string, filterVal string, showMitigations bool, showAlarms bool, showMatches bool, learningMode bool) string { +func GetActiveAlertsPath(startTime *time.Time, endTime *time.Time, filterBy string, filterVal string, + showMitigations bool, showAlarms bool, showMatches bool, learningMode bool, +) string { timeFormatStr := "2006-01-02T15:04:05" v := url.Values{} if startTime != nil { @@ -36,7 +38,8 @@ func GetActiveAlertsPath(startTime *time.Time, endTime *time.Time, filterBy stri } func GetAlertsHistoryPath(startTime *time.Time, endTime *time.Time, filterBy string, filterVal string, sortOrder string, - showMitigations bool, showAlarms bool, showMatches bool, learningMode bool) string { + showMitigations bool, showAlarms bool, showMatches bool, learningMode bool, +) string { timeFormatStr := "2006-01-02T15:04:05" v := url.Values{} if startTime != nil { diff --git a/kentikapi/internal/api_endpoints/custom_applications.go b/kentikapi/internal/endpoints/custom_applications.go similarity index 94% rename from kentikapi/internal/api_endpoints/custom_applications.go rename to kentikapi/internal/endpoints/custom_applications.go index 2f941e30..a1ffdeaf 100644 --- a/kentikapi/internal/api_endpoints/custom_applications.go +++ b/kentikapi/internal/endpoints/custom_applications.go @@ -1,4 +1,4 @@ -package api_endpoints +package endpoints import "fmt" diff --git a/kentikapi/internal/api_endpoints/custom_dimensions.go b/kentikapi/internal/endpoints/custom_dimensions.go similarity index 97% rename from kentikapi/internal/api_endpoints/custom_dimensions.go rename to kentikapi/internal/endpoints/custom_dimensions.go index af6ec00e..afa99b88 100644 --- a/kentikapi/internal/api_endpoints/custom_dimensions.go +++ b/kentikapi/internal/endpoints/custom_dimensions.go @@ -1,4 +1,4 @@ -package api_endpoints +package endpoints import "fmt" diff --git a/kentikapi/internal/api_endpoints/device_labels.go b/kentikapi/internal/endpoints/device_labels.go similarity index 94% rename from kentikapi/internal/api_endpoints/device_labels.go rename to kentikapi/internal/endpoints/device_labels.go index 12e9217c..e57310b7 100644 --- a/kentikapi/internal/api_endpoints/device_labels.go +++ b/kentikapi/internal/endpoints/device_labels.go @@ -1,4 +1,4 @@ -package api_endpoints +package endpoints import ( "fmt" diff --git a/kentikapi/internal/api_endpoints/devices.go b/kentikapi/internal/endpoints/devices.go similarity index 97% rename from kentikapi/internal/api_endpoints/devices.go rename to kentikapi/internal/endpoints/devices.go index fcdd2e6c..7f0efa8c 100644 --- a/kentikapi/internal/api_endpoints/devices.go +++ b/kentikapi/internal/endpoints/devices.go @@ -1,4 +1,4 @@ -package api_endpoints +package endpoints import ( "fmt" diff --git a/kentikapi/internal/api_endpoints/my_kentik_portal.go b/kentikapi/internal/endpoints/my_kentik_portal.go similarity index 95% rename from kentikapi/internal/api_endpoints/my_kentik_portal.go rename to kentikapi/internal/endpoints/my_kentik_portal.go index 9e5f2afe..e74d5a3f 100644 --- a/kentikapi/internal/api_endpoints/my_kentik_portal.go +++ b/kentikapi/internal/endpoints/my_kentik_portal.go @@ -1,4 +1,4 @@ -package api_endpoints +package endpoints import "fmt" diff --git a/kentikapi/internal/api_endpoints/plans.go b/kentikapi/internal/endpoints/plans.go similarity index 68% rename from kentikapi/internal/api_endpoints/plans.go rename to kentikapi/internal/endpoints/plans.go index 8967e784..2dfb6b0e 100644 --- a/kentikapi/internal/api_endpoints/plans.go +++ b/kentikapi/internal/endpoints/plans.go @@ -1,4 +1,4 @@ -package api_endpoints +package endpoints func GetAllPlans() string { return "/plans" diff --git a/kentikapi/internal/api_endpoints/query.go b/kentikapi/internal/endpoints/query.go similarity index 90% rename from kentikapi/internal/api_endpoints/query.go rename to kentikapi/internal/endpoints/query.go index 30dac6af..636fbeac 100644 --- a/kentikapi/internal/api_endpoints/query.go +++ b/kentikapi/internal/endpoints/query.go @@ -1,4 +1,4 @@ -package api_endpoints +package endpoints func QuerySQL() string { return "/query/sql" diff --git a/kentikapi/internal/api_endpoints/saved_filters.go b/kentikapi/internal/endpoints/saved_filters.go similarity index 90% rename from kentikapi/internal/api_endpoints/saved_filters.go rename to kentikapi/internal/endpoints/saved_filters.go index 2253c879..07c39d7f 100644 --- a/kentikapi/internal/api_endpoints/saved_filters.go +++ b/kentikapi/internal/endpoints/saved_filters.go @@ -1,4 +1,4 @@ -package api_endpoints +package endpoints import ( "fmt" diff --git a/kentikapi/internal/api_endpoints/sites.go b/kentikapi/internal/endpoints/sites.go similarity index 93% rename from kentikapi/internal/api_endpoints/sites.go rename to kentikapi/internal/endpoints/sites.go index 211820fc..b8f15f3a 100644 --- a/kentikapi/internal/api_endpoints/sites.go +++ b/kentikapi/internal/endpoints/sites.go @@ -1,4 +1,4 @@ -package api_endpoints +package endpoints import "fmt" diff --git a/kentikapi/internal/api_endpoints/tags.go b/kentikapi/internal/endpoints/tags.go similarity index 87% rename from kentikapi/internal/api_endpoints/tags.go rename to kentikapi/internal/endpoints/tags.go index c9d42e49..b7c557c9 100644 --- a/kentikapi/internal/api_endpoints/tags.go +++ b/kentikapi/internal/endpoints/tags.go @@ -1,4 +1,4 @@ -package api_endpoints +package endpoints import ( "fmt" diff --git a/kentikapi/internal/api_endpoints/types.go b/kentikapi/internal/endpoints/types.go similarity index 81% rename from kentikapi/internal/api_endpoints/types.go rename to kentikapi/internal/endpoints/types.go index 81fad78c..ce635b47 100644 --- a/kentikapi/internal/api_endpoints/types.go +++ b/kentikapi/internal/endpoints/types.go @@ -1,4 +1,4 @@ -package api_endpoints +package endpoints import "github.com/kentik/community_sdk_golang/kentikapi/models" diff --git a/kentikapi/internal/api_endpoints/users.go b/kentikapi/internal/endpoints/users.go similarity index 87% rename from kentikapi/internal/api_endpoints/users.go rename to kentikapi/internal/endpoints/users.go index 393f5a44..984d7fac 100644 --- a/kentikapi/internal/api_endpoints/users.go +++ b/kentikapi/internal/endpoints/users.go @@ -1,4 +1,4 @@ -package api_endpoints +package endpoints import ( "fmt" diff --git a/kentikapi/internal/api_payloads/alerting.go b/kentikapi/internal/payloads/alerting.go similarity index 99% rename from kentikapi/internal/api_payloads/alerting.go rename to kentikapi/internal/payloads/alerting.go index 0477001e..e37cfd9b 100644 --- a/kentikapi/internal/api_payloads/alerting.go +++ b/kentikapi/internal/payloads/alerting.go @@ -1,4 +1,4 @@ -package api_payloads +package payloads import ( "time" diff --git a/kentikapi/internal/api_payloads/custom_application.go b/kentikapi/internal/payloads/custom_application.go similarity index 93% rename from kentikapi/internal/api_payloads/custom_application.go rename to kentikapi/internal/payloads/custom_application.go index 94eeb4bc..25131a24 100644 --- a/kentikapi/internal/api_payloads/custom_application.go +++ b/kentikapi/internal/payloads/custom_application.go @@ -1,4 +1,4 @@ -package api_payloads +package payloads import ( "time" @@ -7,7 +7,7 @@ import ( "github.com/kentik/community_sdk_golang/kentikapi/models" ) -// GetAllCustomApplicationsResponse represents CustomApplicationsAPI GetAll JSON response +// GetAllCustomApplicationsResponse represents CustomApplicationsAPI GetAll JSON response. type GetAllCustomApplicationsResponse []CustomApplicationPayload func (r GetAllCustomApplicationsResponse) ToCustomApplications() (result []models.CustomApplication, err error) { @@ -15,20 +15,20 @@ func (r GetAllCustomApplicationsResponse) ToCustomApplications() (result []model return result, err } -// CreateCustomApplicationRequest represents CustomApplicationsAPI Create JSON request +// CreateCustomApplicationRequest represents CustomApplicationsAPI Create JSON request. type CreateCustomApplicationRequest CustomApplicationPayload -// CreateCustomApplicationResponse represents CustomApplicationsAPI Create JSON response +// CreateCustomApplicationResponse represents CustomApplicationsAPI Create JSON response. type CreateCustomApplicationResponse CustomApplicationPayload func (r CreateCustomApplicationResponse) ToCustomApplication() (models.CustomApplication, error) { return payloadToCustomApplication(CustomApplicationPayload(r)) } -// UpdateCustomApplicationRequest represents CustomApplicationsAPI Update JSON request +// UpdateCustomApplicationRequest represents CustomApplicationsAPI Update JSON request. type UpdateCustomApplicationRequest = CreateCustomApplicationRequest -// UpdateCustomApplicationResponse represents CustomApplicationsAPI Update JSON response +// UpdateCustomApplicationResponse represents CustomApplicationsAPI Update JSON response. type UpdateCustomApplicationResponse = CreateCustomApplicationResponse type CustomApplicationPayload struct { @@ -48,7 +48,7 @@ type CustomApplicationPayload struct { UpdatedDate *time.Time `json:"edate,omitempty" response:"get,put"` // POST doesn't return edate } -// payloadToCustomApplication transforms GET/POST/PUT response payload into CustomApplication +// payloadToCustomApplication transforms GET/POST/PUT response payload into CustomApplication. func payloadToCustomApplication(p CustomApplicationPayload) (models.CustomApplication, error) { return models.CustomApplication{ Name: *p.Name, @@ -65,7 +65,7 @@ func payloadToCustomApplication(p CustomApplicationPayload) (models.CustomApplic }, nil } -// CustomApplicationToPayload prepares POST/PUT request payload: fill only the user-provided fields +// CustomApplicationToPayload prepares POST/PUT request payload: fill only the user-provided fields. func CustomApplicationToPayload(ca models.CustomApplication) CustomApplicationPayload { return CustomApplicationPayload{ Name: &ca.Name, diff --git a/kentikapi/internal/api_payloads/custom_dimension.go b/kentikapi/internal/payloads/custom_dimension.go similarity index 91% rename from kentikapi/internal/api_payloads/custom_dimension.go rename to kentikapi/internal/payloads/custom_dimension.go index 8c1747c3..ee69e6f1 100644 --- a/kentikapi/internal/api_payloads/custom_dimension.go +++ b/kentikapi/internal/payloads/custom_dimension.go @@ -1,10 +1,10 @@ -package api_payloads +package payloads import ( "github.com/kentik/community_sdk_golang/kentikapi/models" ) -// GetAllCustomDimensionsResponse represents CustomDimensionsAPI GetAll JSON response +// GetAllCustomDimensionsResponse represents CustomDimensionsAPI GetAll JSON response. type GetAllCustomDimensionsResponse struct { Payload []CustomDimensionPayload `json:"customDimensions"` } @@ -17,7 +17,7 @@ func (r GetAllCustomDimensionsResponse) ToCustomDimensions() []models.CustomDime return result } -// GetCustomDimensionResponse represents CustomDimensionsAPI Get JSON response +// GetCustomDimensionResponse represents CustomDimensionsAPI Get JSON response. type GetCustomDimensionResponse struct { Payload CustomDimensionPayload `json:"customDimension"` } @@ -26,19 +26,19 @@ func (r GetCustomDimensionResponse) ToCustomDimension() models.CustomDimension { return payloadToCustomDimension(r.Payload) } -// CreateCustomDimensionRequest represents CustomDimensionsAPI Create JSON request +// CreateCustomDimensionRequest represents CustomDimensionsAPI Create JSON request. type CreateCustomDimensionRequest CustomDimensionPayload -// CreateCustomDimensionResponse represents CustomDimensionsAPI Create JSON response +// CreateCustomDimensionResponse represents CustomDimensionsAPI Create JSON response. type CreateCustomDimensionResponse = GetCustomDimensionResponse -// UpdateCustomDimensionRequest represents CustomDimensionsAPI Update JSON request +// UpdateCustomDimensionRequest represents CustomDimensionsAPI Update JSON request. type UpdateCustomDimensionRequest = CreateCustomDimensionRequest -// UpdateCustomDimensionResponse represents CustomDimensionsAPI Update JSON response +// UpdateCustomDimensionResponse represents CustomDimensionsAPI Update JSON response. type UpdateCustomDimensionResponse = GetCustomDimensionResponse -// CustomDimensionPayload represents JSON CustomDimension payload as it is transmitted to and from KentikAPI +// CustomDimensionPayload represents JSON CustomDimension payload as it is transmitted to and from KentikAPI. type CustomDimensionPayload struct { // following fields can appear in request: post/put, response: get/post/put DisplayName string `json:"display_name"` // display_name is always required @@ -53,7 +53,7 @@ type CustomDimensionPayload struct { CompanyID *models.ID `json:"company_id,string" response:"get,post,put"` } -// payloadToCustomDimension transforms GET/POST/PUT response payload into CustomDimension +// payloadToCustomDimension transforms GET/POST/PUT response payload into CustomDimension. func payloadToCustomDimension(p CustomDimensionPayload) models.CustomDimension { return models.CustomDimension{ Name: *p.Name, @@ -65,7 +65,7 @@ func payloadToCustomDimension(p CustomDimensionPayload) models.CustomDimension { } } -// CustomDimensionToPayload prepares POST/PUT request payload: fill only the user-provided fields +// CustomDimensionToPayload prepares POST/PUT request payload: fill only the user-provided fields. func CustomDimensionToPayload(cd models.CustomDimension) CustomDimensionPayload { cdType := string(cd.Type) return CustomDimensionPayload{ diff --git a/kentikapi/internal/api_payloads/device.go b/kentikapi/internal/payloads/device.go similarity index 97% rename from kentikapi/internal/api_payloads/device.go rename to kentikapi/internal/payloads/device.go index a71d16c7..7c4abe6b 100644 --- a/kentikapi/internal/api_payloads/device.go +++ b/kentikapi/internal/payloads/device.go @@ -1,4 +1,4 @@ -package api_payloads +package payloads import ( "time" @@ -7,20 +7,20 @@ import ( "github.com/kentik/community_sdk_golang/kentikapi/models" ) -// CreateDeviceRequest represents DevicesAPI Create JSON request +// CreateDeviceRequest represents DevicesAPI Create JSON request. type CreateDeviceRequest struct { Payload DevicePayload `json:"device"` } -// UpdateDeviceRequest represents DevicesAPI Update JSON request +// UpdateDeviceRequest represents DevicesAPI Update JSON request. type UpdateDeviceRequest CreateDeviceRequest -// ApplyLabelsRequest represents DevicesAPI ApplyLabels JSON request +// ApplyLabelsRequest represents DevicesAPI ApplyLabels JSON request. type ApplyLabelsRequest struct { Labels []labelIDPayload `json:"labels,omitempty"` } -// GetAllDevicesResponse represents DevicesAPI GetAll JSON response +// GetAllDevicesResponse represents DevicesAPI GetAll JSON response. type GetAllDevicesResponse struct { Payload []DevicePayload `json:"devices"` } @@ -30,7 +30,7 @@ func (r GetAllDevicesResponse) ToDevices() (result []models.Device, err error) { return result, err } -// GetDeviceResponse represents DevicesAPI Get JSON response +// GetDeviceResponse represents DevicesAPI Get JSON response. type GetDeviceResponse struct { Payload DevicePayload `json:"device"` } @@ -39,13 +39,13 @@ func (r GetDeviceResponse) ToDevice() (result models.Device, err error) { return payloadToDevice(r.Payload) } -// CreateDeviceResponse represents DevicesAPI Create JSON response +// CreateDeviceResponse represents DevicesAPI Create JSON response. type CreateDeviceResponse = GetDeviceResponse -// UpdateDeviceResponse represents DevicesAPI Update JSON response +// UpdateDeviceResponse represents DevicesAPI Update JSON response. type UpdateDeviceResponse = GetDeviceResponse -// ApplyLabelsResponse represents JSON ApplyLabelsResponse payload as it is transmitted from KentikAPI +// ApplyLabelsResponse represents JSON ApplyLabelsResponse payload as it is transmitted from KentikAPI. type ApplyLabelsResponse struct { ID models.ID `json:"id,string"` DeviceName string `json:"device_name"` @@ -60,7 +60,7 @@ func (r *ApplyLabelsResponse) ToAppliedLabels() (models.AppliedLabels, error) { return models.AppliedLabels{ID: r.ID, DeviceName: r.DeviceName, Labels: labels}, nil } -// DevicePayload represents JSON Device payload as it is transmitted to and from KentikAPI +// DevicePayload represents JSON Device payload as it is transmitted to and from KentikAPI. type DevicePayload struct { // following fields can appear in request: post/put, response: get/post/put PlanID *models.ID `json:"plan_id,omitempty" request:"post"` @@ -102,7 +102,7 @@ type DevicePayload struct { BGPPeerIP6 *string `json:"bgpPeerIP6,omitempty"` } -// payloadToDevice transforms GET/POST/PUT response payload into Device +// payloadToDevice transforms GET/POST/PUT response payload into Device. func payloadToDevice(p DevicePayload) (models.Device, error) { plan, err := payloadToDevicePlan(*p.Plan) if err != nil { @@ -174,7 +174,7 @@ func deviceBGPTypeFromStringPtr(s *string) *models.DeviceBGPType { return &result } -// DeviceToPayload prepares POST/PUT request payload: fill only the user-provided fields +// DeviceToPayload prepares POST/PUT request payload: fill only the user-provided fields. func DeviceToPayload(d models.Device) DevicePayload { return DevicePayload{ DeviceName: &d.DeviceName, @@ -216,7 +216,7 @@ func deviceBGPTypeToStringPtr(t *models.DeviceBGPType) *string { return &result } -// allInterfacesPayload represents JSON Device.AllInterfaces payload as it is transmitted from KentikAPI +// allInterfacesPayload represents JSON Device.AllInterfaces payload as it is transmitted from KentikAPI. type allInterfacesPayload struct { DeviceID models.ID `json:"device_id,string,omitempty"` SNMPSpeed float64 `json:"snmp_speed,string,omitempty"` @@ -233,7 +233,7 @@ func payloadToAllInterfaces(p allInterfacesPayload) (models.AllInterfaces, error }, nil } -// snmpv3ConfPayload represents JSON Device.SNMPv3Conf payload as it is transmitted to and from KentikAPI +// snmpv3ConfPayload represents JSON Device.SNMPv3Conf payload as it is transmitted to and from KentikAPI. type snmpv3ConfPayload struct { UserName string `json:"UserName,omitempty"` AuthenticationProtocol *string `json:"AuthenticationProtocol,omitempty"` @@ -299,7 +299,7 @@ func snmp3ConfToPayload(d *models.SNMPv3Conf) *snmpv3ConfPayload { // deviceLabelPayload represents JSON Device.Label payload as it is transmitted from KentikAPI. // deviceLabelPayload embedded under Device differs from standalone LabelPayload in that it lacks devices list, -// and differs in field names, eg. cdate vs created_date, edate vs updated_date +// and differs in field names, eg. cdate vs created_date, edate vs updated_date. type deviceLabelPayload struct { ID models.ID `json:"id"` Color string `json:"color"` @@ -367,6 +367,7 @@ type devicePlanPayload struct { Devices []planDevicePayload `json:"devices"` } +//nolint:dupl func payloadToDevicePlan(p devicePlanPayload) (models.DevicePlan, error) { var deviceTypes []models.PlanDeviceType err := utils.ConvertList(p.DeviceTypes, payloadToPlanDeviceType, &deviceTypes) @@ -399,11 +400,12 @@ func payloadToDevicePlan(p devicePlanPayload) (models.DevicePlan, error) { }, nil } -// labelIDPayload represents JSON ApplyLabels.LabelID payload as it is transmitted to KentikAPI +// labelIDPayload represents JSON ApplyLabels.LabelID payload as it is transmitted to KentikAPI. type labelIDPayload struct { ID int `json:"id"` } +//nolint:revive // labelIDPayLoad doesn't need to be exported func LabelIDsToPayload(ids []models.ID) []labelIDPayload { result := make([]labelIDPayload, 0, len(ids)) for _, id := range ids { diff --git a/kentikapi/internal/api_payloads/device_label.go b/kentikapi/internal/payloads/device_label.go similarity index 92% rename from kentikapi/internal/api_payloads/device_label.go rename to kentikapi/internal/payloads/device_label.go index 322a47c7..3a56a38e 100644 --- a/kentikapi/internal/api_payloads/device_label.go +++ b/kentikapi/internal/payloads/device_label.go @@ -1,4 +1,4 @@ -package api_payloads +package payloads import ( "time" @@ -7,7 +7,7 @@ import ( "github.com/kentik/community_sdk_golang/kentikapi/models" ) -// GetAllDeviceLabelsResponse represents DeviceLabelsAPI GetAll JSON response +// GetAllDeviceLabelsResponse represents DeviceLabelsAPI GetAll JSON response. type GetAllDeviceLabelsResponse []DeviceLabelPayload func (r GetAllDeviceLabelsResponse) ToDeviceLabels() (result []models.DeviceLabel, err error) { @@ -15,31 +15,31 @@ func (r GetAllDeviceLabelsResponse) ToDeviceLabels() (result []models.DeviceLabe return result, err } -// GetDeviceLabelResponse represents DeviceLabelsAPI Get JSON response +// GetDeviceLabelResponse represents DeviceLabelsAPI Get JSON response. type GetDeviceLabelResponse DeviceLabelPayload func (r GetDeviceLabelResponse) ToDeviceLabel() (models.DeviceLabel, error) { return PayloadToDeviceLabel(DeviceLabelPayload(r)) } -// CreateDeviceLabelRequest represents DeviceLabelsAPI Create JSON request +// CreateDeviceLabelRequest represents DeviceLabelsAPI Create JSON request. type CreateDeviceLabelRequest DeviceLabelPayload -// CreateDeviceLabelResponse represents DeviceLabelsAPI Create JSON response +// CreateDeviceLabelResponse represents DeviceLabelsAPI Create JSON response. type CreateDeviceLabelResponse = GetDeviceLabelResponse -// UpdateDeviceLabelRequest represents DeviceLabelsAPI Update JSON request +// UpdateDeviceLabelRequest represents DeviceLabelsAPI Update JSON request. type UpdateDeviceLabelRequest DeviceLabelPayload -// UpdateDeviceLabelResponse represents DeviceLabelsAPI Update JSON response +// UpdateDeviceLabelResponse represents DeviceLabelsAPI Update JSON response. type UpdateDeviceLabelResponse = GetDeviceLabelResponse -// DeleteDeviceLabelResponse represents DeviceLabelsAPI Delete JSON response. Yes delete returns an object +// DeleteDeviceLabelResponse represents DeviceLabelsAPI Delete JSON response. Yes delete returns an object. type DeleteDeviceLabelResponse struct { Success bool `json:"success"` } -// DeviceLabelPayload represents JSON DeviceLabel payload as it is transmitted from KentikAPI +// DeviceLabelPayload represents JSON DeviceLabel payload as it is transmitted from KentikAPI. type DeviceLabelPayload struct { // following fields can appear in request: post/put, response: get/post/put Name string `json:"name"` // name is always required @@ -55,14 +55,15 @@ type DeviceLabelPayload struct { } type deviceItemPayload struct { - // following fields can appear in request: none, response: get, put. Not in post as newly created label is not assigned to any device + // following fields can appear in request: none, response: get, put. + // Not in post as newly created label is not assigned to any device ID models.ID `json:"id,string"` DeviceName string `json:"device_name"` DeviceSubtype string `json:"device_subtype"` DeviceType *string `json:"device_type"` // device_type is not always returned } -// PayloadToDeviceLabel transforms GET/POST/PUT response payload into DeviceLabel +// PayloadToDeviceLabel transforms GET/POST/PUT response payload into DeviceLabel. func PayloadToDeviceLabel(p DeviceLabelPayload) (models.DeviceLabel, error) { var devices []models.DeviceItem err := utils.ConvertList(p.Devices, payloadToDeviceItem, &devices) @@ -91,7 +92,7 @@ func payloadToDeviceItem(p deviceItemPayload) (models.DeviceItem, error) { }, nil } -// DeviceLabelToPayload prepares POST/PUT request payload: fill only the user-provided fields +// DeviceLabelToPayload prepares POST/PUT request payload: fill only the user-provided fields. func DeviceLabelToPayload(l models.DeviceLabel) DeviceLabelPayload { return DeviceLabelPayload{ Name: l.Name, diff --git a/kentikapi/internal/api_payloads/interface.go b/kentikapi/internal/payloads/interface.go similarity index 89% rename from kentikapi/internal/api_payloads/interface.go rename to kentikapi/internal/payloads/interface.go index af163314..a10e3d73 100644 --- a/kentikapi/internal/api_payloads/interface.go +++ b/kentikapi/internal/payloads/interface.go @@ -1,4 +1,4 @@ -package api_payloads +package payloads import ( "encoding/json" @@ -10,7 +10,7 @@ import ( // Note: InterfacesAPI belong under DevicesAPI but it is vast so it lives in a separate file -// GetInterfaceResponse represents DevicesAPI.InterfacesAPI GetAll JSON response +// GetAllInterfacesResponse represents DevicesAPI.InterfacesAPI GetAll JSON response. type GetAllInterfacesResponse []InterfacePayload func (r GetAllInterfacesResponse) ToInterfaces() (result []models.Interface, err error) { @@ -18,7 +18,7 @@ func (r GetAllInterfacesResponse) ToInterfaces() (result []models.Interface, err return result, err } -// GetInterfaceResponse represents DevicesAPI.InterfacesAPI Get JSON response +// GetInterfaceResponse represents DevicesAPI.InterfacesAPI Get JSON response. type GetInterfaceResponse struct { Interface InterfacePayload `json:"interface"` } @@ -27,34 +27,37 @@ func (r GetInterfaceResponse) ToInterface() (result models.Interface, err error) return payloadToInterface(r.Interface) } -// CreateInterfaceRequest represents DevicesAPI.InterfacesAPI Create JSON request +// CreateInterfaceRequest represents DevicesAPI.InterfacesAPI Create JSON request. type CreateInterfaceRequest InterfacePayload -// CreateInterfaceResponse represents DevicesAPI.InterfacesAPI Create JSON response +// CreateInterfaceResponse represents DevicesAPI.InterfacesAPI Create JSON response. type CreateInterfaceResponse InterfacePayload func (r CreateInterfaceResponse) ToInterface() (result models.Interface, err error) { return payloadToInterface(InterfacePayload(r)) } -// UpdateInterfaceRequest represents DevicesAPI.InterfacesAPI Create JSON request +// UpdateInterfaceRequest represents DevicesAPI.InterfacesAPI Create JSON request. type UpdateInterfaceRequest InterfacePayload -// UpdateInterfaceResponse represents DevicesAPI.InterfacesAPI Update JSON response +// UpdateInterfaceResponse represents DevicesAPI.InterfacesAPI Update JSON response. type UpdateInterfaceResponse = CreateInterfaceResponse -// InterfacePayload represents JSON Interface payload as it is transmitted to and from KentikAPI +// InterfacePayload represents JSON Interface payload as it is transmitted to and from KentikAPI. type InterfacePayload struct { // following fields can appear in request: post/put, response: get/post/put - SNMPID *models.ID `json:"snmp_id,string,omitempty" request:"post" response:"get,post,put"` - SNMPSpeed IntAsString `json:"snmp_speed,omitempty"` // caveat, GET returns snmp_speed as string but POST and PUT as int + SNMPID *models.ID `json:"snmp_id,string,omitempty" request:"post" response:"get,post,put"` + SNMPSpeed IntAsString `json:"snmp_speed,omitempty"` // caveat, GET returns snmp_speed as string + // but POST and PUT as int InterfaceDescription *string `json:"interface_description,omitempty" request:"post" response:"get,post,put"` SNMPAlias *string `json:"snmp_alias,omitempty"` InterfaceIP *string `json:"interface_ip,omitempty"` InterfaceIPNetmask *string `json:"interface_ip_netmask,omitempty"` - VRF *vrfAttributesPayload `json:"vrf,omitempty"` // caveat, for non-set vrf GET returns vrf as null, but POST and PUT as empty object "{}" - VRFID *IntAsString `json:"vrf_id,omitempty"` // caveat, GET returns vrf_id as string but POST and PUT as int - SecondaryIPs []secondaryIPPayload `json:"secondary_ips,omitempty"` + VRF *vrfAttributesPayload `json:"vrf,omitempty"` // caveat, for non-set vrf GET returns vrf as null, + // but POST and PUT as empty object "{}" + VRFID *IntAsString `json:"vrf_id,omitempty"` // caveat, GET returns vrf_id as string + // but POST and PUT as int + SecondaryIPs []secondaryIPPayload `json:"secondary_ips,omitempty"` // following fields can appear in request: none, response: get/post/put ID *models.ID `json:"id,string,omitempty" response:"get,post,put"` @@ -125,7 +128,7 @@ func payloadToInterface(p InterfacePayload) (models.Interface, error) { }, nil } -// InterfaceToPayload prepares POST/PUT request payload: fill only the user-provided fields +// InterfaceToPayload prepares POST/PUT request payload: fill only the user-provided fields. func InterfaceToPayload(i models.Interface) (InterfacePayload, error) { var secondaryIPs []secondaryIPPayload err := utils.ConvertList(i.SecondaryIPS, secondaryIPToPayload, &secondaryIPs) @@ -147,7 +150,7 @@ func InterfaceToPayload(i models.Interface) (InterfacePayload, error) { } // vrfAttributesPayload represents JSON Interface.VRFAttributes payload as it is transmitted to and from KentikAPI -// Note: it is returned only in get response, for post and put responses empty object is returned but vrf_id is set +// Note: it is returned only in get response, for post and put responses empty object is returned but vrf_id is set. type vrfAttributesPayload struct { // following fields can appear in request: post/put, response: get Name string `json:"name"` @@ -181,7 +184,7 @@ func payloadToVRFAttributes(p *vrfAttributesPayload) *models.VRFAttributes { } } -// vrfAttributesToPayload prepares POST/PUT request payload: fill only the user-provided fields +// vrfAttributesToPayload prepares POST/PUT request payload: fill only the user-provided fields. func vrfAttributesToPayload(a *models.VRFAttributes) *vrfAttributesPayload { if a == nil { return nil @@ -196,7 +199,7 @@ func vrfAttributesToPayload(a *models.VRFAttributes) *vrfAttributesPayload { } } -// secondaryIPPayload represents JSON Interface.SecondaryIPPayload payload as it is transmitted to and from KentikAPI +// secondaryIPPayload represents JSON Interface.SecondaryIPPayload payload as it is transmitted to and from KentikAPI. type secondaryIPPayload struct { // following fields can appear in request: post/put, response: get/post/put Address string `json:"address"` @@ -210,7 +213,7 @@ func payloadToSecondaryIP(p secondaryIPPayload) (models.SecondaryIP, error) { }, nil } -// secondaryIPToPayload prepares POST/PUT request payload: fill only the user-provided fields +// secondaryIPToPayload prepares POST/PUT request payload: fill only the user-provided fields. func secondaryIPToPayload(s models.SecondaryIP) (secondaryIPPayload, error) { return secondaryIPPayload{ Address: s.Address, @@ -218,7 +221,7 @@ func secondaryIPToPayload(s models.SecondaryIP) (secondaryIPPayload, error) { }, nil } -// topNextHopASNPayload represents JSON Interface.TopNextHopASNPayload payload as it is transmitted from KentikAPI +// topNextHopASNPayload represents JSON Interface.TopNextHopASNPayload payload as it is transmitted from KentikAPI. type topNextHopASNPayload struct { // following fields can appear in request: post/put, response: get/post/put ASN int `json:"ASN"` diff --git a/kentikapi/internal/api_payloads/plan.go b/kentikapi/internal/payloads/plan.go similarity index 94% rename from kentikapi/internal/api_payloads/plan.go rename to kentikapi/internal/payloads/plan.go index fdef22ce..e93c63e6 100644 --- a/kentikapi/internal/api_payloads/plan.go +++ b/kentikapi/internal/payloads/plan.go @@ -1,4 +1,4 @@ -package api_payloads +package payloads import ( "time" @@ -7,7 +7,7 @@ import ( "github.com/kentik/community_sdk_golang/kentikapi/models" ) -// GetAllPlansResponse represents PlansAPI GetAll JSON response +// GetAllPlansResponse represents PlansAPI GetAll JSON response. type GetAllPlansResponse struct { Plans []PlanPayload `json:"plans"` } @@ -17,7 +17,7 @@ func (r GetAllPlansResponse) ToPlans() (result []models.Plan, err error) { return result, err } -// PlanPayload represents JSON Plan payload as it is transmitted from KentikAPI +// PlanPayload represents JSON Plan payload as it is transmitted from KentikAPI. type PlanPayload struct { // following fields can appear in request: none, response: get ID models.ID `json:"id"` @@ -37,6 +37,7 @@ type PlanPayload struct { Devices []planDevicePayload `json:"devices"` } +//nolint:dupl func payloadToPlan(p PlanPayload) (models.Plan, error) { var deviceTypes []models.PlanDeviceType err := utils.ConvertList(p.DeviceTypes, payloadToPlanDeviceType, &deviceTypes) @@ -69,7 +70,7 @@ func payloadToPlan(p PlanPayload) (models.Plan, error) { }, nil } -// planDeviceTypePayload represents JSON Plan.DeviceTypes payload as it is transmitted from KentikAPI +// planDeviceTypePayload represents JSON Plan.DeviceTypes payload as it is transmitted from KentikAPI. type planDeviceTypePayload struct { DeviceType string `json:"device_type"` } @@ -78,7 +79,7 @@ func payloadToPlanDeviceType(p planDeviceTypePayload) (models.PlanDeviceType, er return models.PlanDeviceType{DeviceType: p.DeviceType}, nil } -// planDevicePayload represents JSON Plan.Devices payload as it is transmitted from KentikAPI +// planDevicePayload represents JSON Plan.Devices payload as it is transmitted from KentikAPI. type planDevicePayload struct { DeviceName string `json:"device_name"` DeviceType string `json:"device_type"` diff --git a/kentikapi/internal/api_payloads/populator.go b/kentikapi/internal/payloads/populator.go similarity index 95% rename from kentikapi/internal/api_payloads/populator.go rename to kentikapi/internal/payloads/populator.go index ea2d89de..e428aa5d 100644 --- a/kentikapi/internal/api_payloads/populator.go +++ b/kentikapi/internal/payloads/populator.go @@ -1,4 +1,4 @@ -package api_payloads +package payloads import ( "time" @@ -6,12 +6,12 @@ import ( "github.com/kentik/community_sdk_golang/kentikapi/models" ) -// CreatePopulatorRequest represents CustomDimensionsAPI.Populators Create JSON request +// CreatePopulatorRequest represents CustomDimensionsAPI.Populators Create JSON request. type CreatePopulatorRequest struct { Payload PopulatorPayload `json:"populator"` } -// CreatePopulatorResponse represents CustomDimensionsAPI.Populators Create JSON response +// CreatePopulatorResponse represents CustomDimensionsAPI.Populators Create JSON response. type CreatePopulatorResponse struct { Payload PopulatorPayload `json:"populator"` } @@ -20,13 +20,13 @@ func (r CreatePopulatorResponse) ToPopulator() models.Populator { return payloadToPopulator(r.Payload) } -// UpdatePopulatorRequest represents CustomDimensionsAPI.Populators Update JSON request +// UpdatePopulatorRequest represents CustomDimensionsAPI.Populators Update JSON request. type UpdatePopulatorRequest = CreatePopulatorRequest -// UpdatePopulatorResponse represents CustomDimensionsAPI.Populators Update JSON response +// UpdatePopulatorResponse represents CustomDimensionsAPI.Populators Update JSON response. type UpdatePopulatorResponse = CreatePopulatorResponse -// PopulatorPayload represents JSON Populator payload as it is transmitted to and from KentikAPI +// PopulatorPayload represents JSON Populator payload as it is transmitted to and from KentikAPI. type PopulatorPayload struct { // following fields can appear in request: post/put, response: get/post/put Direction string `json:"direction"` // direction is always required @@ -69,7 +69,7 @@ func payloadToPopulators(p []PopulatorPayload) []models.Populator { return result } -// payloadToPopulator transforms GET/POST/PUT response payload into Populator +// payloadToPopulator transforms GET/POST/PUT response payload into Populator. func payloadToPopulator(p PopulatorPayload) models.Populator { return models.Populator{ Direction: models.PopulatorDirection(p.Direction), @@ -103,7 +103,7 @@ func payloadToPopulator(p PopulatorPayload) models.Populator { } } -// PopulatorToPayload prepares POST/PUT request payload: fill only the user-provided fields +// PopulatorToPayload prepares POST/PUT request payload: fill only the user-provided fields. func PopulatorToPayload(p models.Populator) PopulatorPayload { return PopulatorPayload{ Direction: string(p.Direction), diff --git a/kentikapi/internal/api_payloads/query.go b/kentikapi/internal/payloads/query.go similarity index 74% rename from kentikapi/internal/api_payloads/query.go rename to kentikapi/internal/payloads/query.go index 53a22e21..3fd72158 100644 --- a/kentikapi/internal/api_payloads/query.go +++ b/kentikapi/internal/payloads/query.go @@ -1,4 +1,4 @@ -package api_payloads +package payloads import ( "encoding/base64" @@ -10,12 +10,12 @@ import ( "github.com/kentik/community_sdk_golang/kentikapi/models" ) -// QuerySQLRequest represents QueryAPI SQL JSON request +// QuerySQLRequest represents QueryAPI SQL JSON request. type QuerySQLRequest struct { Query string `json:"query"` } -// QuerySQLResponse represents QueryAPI SQL JSON response +// QuerySQLResponse represents QueryAPI SQL JSON response. type QuerySQLResponse struct { Rows []interface{} `json:"rows"` // contents depend on used sql query } @@ -24,10 +24,10 @@ func (r QuerySQLResponse) ToQuerySQLResult() models.QuerySQLResult { return models.QuerySQLResult{Rows: r.Rows} } -// QueryObjectRequest represents QueryAPI Data/Chart/URL JSON request +// QueryObjectRequest represents QueryAPI Data/Chart/URL JSON request. type QueryObjectRequest queryObjectPayload -// QueryDataResponse represents QueryAPI Data JSON response +// QueryDataResponse represents QueryAPI Data JSON response. type QueryDataResponse struct { Results []interface{} `json:"results"` // contents depend on used query object } @@ -36,7 +36,7 @@ func (r QueryDataResponse) ToQueryDataResult() models.QueryDataResult { return models.QueryDataResult{Results: r.Results} } -// QueryURLResponse represents QueryAPI URL JSON response +// QueryURLResponse represents QueryAPI URL JSON response. type QueryURLResponse string func (r QueryURLResponse) ToQueryURLResult() models.QueryURLResult { @@ -44,7 +44,7 @@ func (r QueryURLResponse) ToQueryURLResult() models.QueryURLResult { return models.QueryURLResult{URL: unquotedURL} } -// QueryChartResponse represents QueryAPI Chart JSON response +// QueryChartResponse represents QueryAPI Chart JSON response. type QueryChartResponse struct { DataURI string `json:"dataUri"` // like: "data:image/png;base64,iVBORw0KGgoAAAA..." } @@ -121,6 +121,7 @@ type queryObjectPayload struct { ImageType *string `json:"imageType,omitempty"` } +//nolint:revive // queryObjectPayLoad doesn't need to be exported func QueryObjectToPayload(q models.QueryObject) (queryObjectPayload, error) { var queries []queryArrayItemPayload if err := utils.ConvertList(q.Queries, queryArrayItemToPayload, &queries); err != nil { @@ -146,6 +147,7 @@ type queryArrayItemPayload struct { IsOverlay *bool `json:"isOverlay,omitempty"` } +//nolint:nilerr func queryArrayItemToPayload(i models.QueryArrayItem) (queryArrayItemPayload, error) { query, err := queryToPayload(i.Query) if err != nil { @@ -161,32 +163,33 @@ func queryArrayItemToPayload(i models.QueryArrayItem) (queryArrayItemPayload, er } type queryPayload struct { - Metric string `json:"metric"` - Dimension []string `json:"dimension,omitempty"` - FiltersObj *filtersPayload `json:"filters_obj,omitempty"` - SavedFilters []savedFilterPayload `json:"saved_filters,omitempty"` - MatrixBy []string `json:"matrixBy" request:"post"` // matrixBy is required in request even if empty. Otherwise Chart query hangs - CIDR *int `json:"cidr,omitempty"` - CIDR6 *int `json:"cidr6,omitempty"` - PPSThreshold *int `json:"pps_threshold,omitempty"` - TopX int `json:"topx"` - Depth int `json:"depth"` - FastData string `json:"fastData"` - TimeFormat string `json:"time_format"` - HostnameLookup bool `json:"hostname_lookup"` - LookbackSeconds int `json:"lookback_seconds"` - StartingTime *string `json:"starting_time,omitempty"` // format YYYY-MM-DD HH:mm:00 - EndingTime *string `json:"ending_time,omitempty"` // format YYYY-MM-DD HH:mm:00 - AllSelected *bool `json:"all_selected,omitempty"` - DeviceName []string `json:"device_name" request:"post"` // device_name is required in request even if empty - Descriptor string `json:"descriptor"` - Aggregates []aggregatePayload `json:"aggregates,omitempty"` - Outsort *string `json:"outsort,omitempty"` - QueryTitle string `json:"query_title"` - VizType *string `json:"viz_type,omitempty"` - ShowOverlay *bool `json:"show_overlay,omitempty"` - OverlayDay *int `json:"overlay_day,omitempty"` - SyncAxes *bool `json:"sync_axes,omitempty"` + Metric string `json:"metric"` + Dimension []string `json:"dimension,omitempty"` + FiltersObj *filtersPayload `json:"filters_obj,omitempty"` + SavedFilters []savedFilterPayload `json:"saved_filters,omitempty"` + MatrixBy []string `json:"matrixBy" request:"post"` // matrixBy is required in request even if empty. + // Otherwise Chart query hangs + CIDR *int `json:"cidr,omitempty"` + CIDR6 *int `json:"cidr6,omitempty"` + PPSThreshold *int `json:"pps_threshold,omitempty"` + TopX int `json:"topx"` + Depth int `json:"depth"` + FastData string `json:"fastData"` + TimeFormat string `json:"time_format"` + HostnameLookup bool `json:"hostname_lookup"` + LookbackSeconds int `json:"lookback_seconds"` + StartingTime *string `json:"starting_time,omitempty"` // format YYYY-MM-DD HH:mm:00 + EndingTime *string `json:"ending_time,omitempty"` // format YYYY-MM-DD HH:mm:00 + AllSelected *bool `json:"all_selected,omitempty"` + DeviceName []string `json:"device_name" request:"post"` // device_name is required in request even if empty + Descriptor string `json:"descriptor"` + Aggregates []aggregatePayload `json:"aggregates,omitempty"` + Outsort *string `json:"outsort,omitempty"` + QueryTitle string `json:"query_title"` + VizType *string `json:"viz_type,omitempty"` + ShowOverlay *bool `json:"show_overlay,omitempty"` + OverlayDay *int `json:"overlay_day,omitempty"` + SyncAxes *bool `json:"sync_axes,omitempty"` } func queryToPayload(q models.Query) (queryPayload, error) { @@ -252,7 +255,7 @@ func filtersToPayload(f *models.Filters) *filtersPayload { var filterGroupsPayloads []filterGroupsPayload for _, i := range f.FilterGroups { - filterGroupsPayloads = append(filterGroupsPayloads, FilterGroupsToPayload(i)) + filterGroupsPayloads = append(filterGroupsPayloads, filterGroupsToPayload(i)) } return &filtersPayload{ @@ -288,6 +291,6 @@ func FormatQueryTime(t *time.Time) *string { return nil } layout := "2006-01-02 15:04" - result := t.Format(layout) + ":00" //"YYYY-MM-DD HH:mm:00" + result := t.Format(layout) + ":00" // "YYYY-MM-DD HH:mm:00" return &result } diff --git a/kentikapi/internal/api_payloads/query_test.go b/kentikapi/internal/payloads/query_test.go similarity index 74% rename from kentikapi/internal/api_payloads/query_test.go rename to kentikapi/internal/payloads/query_test.go index 90d5136d..8277387d 100644 --- a/kentikapi/internal/api_payloads/query_test.go +++ b/kentikapi/internal/payloads/query_test.go @@ -1,21 +1,23 @@ -package api_payloads_test +package payloads_test import ( "encoding/base64" "testing" "time" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" + "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" "github.com/kentik/community_sdk_golang/kentikapi/models" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestQueryChartResponsePNGToQueryChartResult(t *testing.T) { + t.Parallel() + // arrange data := "ImagePNGEncodedBase64str" decodedData := base64Decode(t, data) - response := api_payloads.QueryChartResponse{DataURI: "data:image/png;base64," + data} + response := payloads.QueryChartResponse{DataURI: "data:image/png;base64," + data} // act result, err := response.ToQueryChartResult() @@ -27,10 +29,12 @@ func TestQueryChartResponsePNGToQueryChartResult(t *testing.T) { } func TestQueryChartResponseJPEGToQueryChartResult(t *testing.T) { + t.Parallel() + // arrange data := "ImageJPGEncodedBase64str" decodedData := base64Decode(t, data) - response := api_payloads.QueryChartResponse{DataURI: "data:image/jpeg;base64," + data} + response := payloads.QueryChartResponse{DataURI: "data:image/jpeg;base64," + data} // act result, err := response.ToQueryChartResult() @@ -42,10 +46,12 @@ func TestQueryChartResponseJPEGToQueryChartResult(t *testing.T) { } func TestQueryChartResponseSVGToQueryChartResult(t *testing.T) { + t.Parallel() + // arrange data := "ImageSVGEncodedBase64str" decodedData := base64Decode(t, data) - response := api_payloads.QueryChartResponse{DataURI: "data:image/svg+xml;base64," + data} + response := payloads.QueryChartResponse{DataURI: "data:image/svg+xml;base64," + data} // act result, err := response.ToQueryChartResult() @@ -57,10 +63,12 @@ func TestQueryChartResponseSVGToQueryChartResult(t *testing.T) { } func TestQueryChartResponsePDFToQueryChartResult(t *testing.T) { + t.Parallel() + // arrange data := "ApplicationPDFEncodedBase64str==" decodedData := base64Decode(t, data) - response := api_payloads.QueryChartResponse{DataURI: "data:application/pdf;base64," + data} + response := payloads.QueryChartResponse{DataURI: "data:application/pdf;base64," + data} // act result, err := response.ToQueryChartResult() @@ -72,9 +80,11 @@ func TestQueryChartResponsePDFToQueryChartResult(t *testing.T) { } func TestUnknownFormatResultsInError(t *testing.T) { + t.Parallel() + // arrange data := "ImageBMPEncodedBase64str==" - response := api_payloads.QueryChartResponse{DataURI: "data:image/bmp;base64," + data} + response := payloads.QueryChartResponse{DataURI: "data:image/bmp;base64," + data} // act _, err := response.ToQueryChartResult() @@ -84,9 +94,11 @@ func TestUnknownFormatResultsInError(t *testing.T) { } func TestUnknownEncodingResultsInError(t *testing.T) { + t.Parallel() + // arrange data := "ImagePNGEncodedBase32str==" - response := api_payloads.QueryChartResponse{DataURI: "data:image/png;base32," + data} + response := payloads.QueryChartResponse{DataURI: "data:image/png;base32," + data} // act _, err := response.ToQueryChartResult() @@ -96,11 +108,13 @@ func TestUnknownEncodingResultsInError(t *testing.T) { } func TestFormatQueryTimeNonNil(t *testing.T) { + t.Parallel() + // arrange datetime := time.Date(2001, 3, 9, 6, 45, 53, 111, time.UTC) // act - queryTime := api_payloads.FormatQueryTime(&datetime) + queryTime := payloads.FormatQueryTime(&datetime) // assert require.NotNil(t, queryTime) @@ -108,11 +122,13 @@ func TestFormatQueryTimeNonNil(t *testing.T) { } func TestFormatQueryTimeNil(t *testing.T) { + t.Parallel() + // arrange - var datetime *time.Time = nil + var datetime *time.Time // act - queryTime := api_payloads.FormatQueryTime(datetime) + queryTime := payloads.FormatQueryTime(datetime) // assert assert.Nil(t, queryTime) diff --git a/kentikapi/internal/api_payloads/saved_filter.go b/kentikapi/internal/payloads/saved_filter.go similarity index 92% rename from kentikapi/internal/api_payloads/saved_filter.go rename to kentikapi/internal/payloads/saved_filter.go index b93f6ee8..8ddc877e 100644 --- a/kentikapi/internal/api_payloads/saved_filter.go +++ b/kentikapi/internal/payloads/saved_filter.go @@ -1,4 +1,4 @@ -package api_payloads +package payloads import ( "time" @@ -67,6 +67,7 @@ func (p savedFilterPayload) ToSavedFilter() (models.SavedFilter, error) { }, nil } +//nolint:revive // savedFilterPayLoad doesn't need to be exported func SavedFilterToPayload(sf models.SavedFilter) savedFilterPayload { return savedFilterPayload{ ID: IntAsString(sf.ID), @@ -113,10 +114,11 @@ func (p filtersPayload) ToFilters() (models.Filters, error) { }, nil } +//nolint:revive // FiltersToPayload could be unexported but filtersToPayload already exists func FiltersToPayload(f models.Filters) filtersPayload { var filterGroups []filterGroupsPayload for _, fg := range f.FilterGroups { - filterGroups = append(filterGroups, FilterGroupsToPayload(fg)) + filterGroups = append(filterGroups, filterGroupsToPayload(fg)) } return filtersPayload{ @@ -152,10 +154,10 @@ func (p filterGroupsPayload) ToFilterGroups() (models.FilterGroups, error) { }, nil } -func FilterGroupsToPayload(fg models.FilterGroups) filterGroupsPayload { +func filterGroupsToPayload(fg models.FilterGroups) filterGroupsPayload { var filters []filterPayload for _, f := range fg.Filters { - filters = append(filters, FilterToPayload(f)) + filters = append(filters, filterToPayload(f)) } return filterGroupsPayload{ @@ -184,7 +186,7 @@ func (p filterPayload) ToFilter() (models.Filter, error) { }, nil } -func FilterToPayload(f models.Filter) filterPayload { +func filterToPayload(f models.Filter) filterPayload { return filterPayload{ FilterField: f.FilterField, ID: f.ID, diff --git a/kentikapi/internal/api_payloads/site.go b/kentikapi/internal/payloads/site.go similarity index 80% rename from kentikapi/internal/api_payloads/site.go rename to kentikapi/internal/payloads/site.go index 7d94f4fb..111ecb0e 100644 --- a/kentikapi/internal/api_payloads/site.go +++ b/kentikapi/internal/payloads/site.go @@ -1,11 +1,11 @@ -package api_payloads +package payloads import ( "github.com/kentik/community_sdk_golang/kentikapi/internal/utils" "github.com/kentik/community_sdk_golang/kentikapi/models" ) -// GetSiteResponse represents SitesAPI Get JSON response +// GetSiteResponse represents SitesAPI Get JSON response. type GetSiteResponse struct { Payload SitePayload `json:"site"` } @@ -14,7 +14,7 @@ func (r GetSiteResponse) ToSite() (result models.Site, err error) { return payloadToSite(r.Payload) } -// GetAllSitesResponse represents SitesAPI GetAll JSON response +// GetAllSitesResponse represents SitesAPI GetAll JSON response. type GetAllSitesResponse struct { Payload []SitePayload `json:"sites"` } @@ -24,21 +24,21 @@ func (r GetAllSitesResponse) ToSites() (result []models.Site, err error) { return result, err } -// CreateSiteRequest represents SitesAPI Create JSON request +// CreateSiteRequest represents SitesAPI Create JSON request. type CreateSiteRequest struct { Payload SitePayload `json:"site"` } -// CreateSiteResponse represents SitesAPI Create JSON Response +// CreateSiteResponse represents SitesAPI Create JSON Response. type CreateSiteResponse = GetSiteResponse -// UpdateSiteRequest represents SitesAPI Update JSON request +// UpdateSiteRequest represents SitesAPI Update JSON request. type UpdateSiteRequest = CreateSiteRequest -// UpdateSiteResponse represents SitesAPI Update JSON response +// UpdateSiteResponse represents SitesAPI Update JSON response. type UpdateSiteResponse = CreateSiteResponse -// SitePayload represents JSON Plan payload as it is transmitted to and from KentikAPI +// SitePayload represents JSON Plan payload as it is transmitted to and from KentikAPI. type SitePayload struct { ID IntAsString `json:"id"` // caveat, POST and GET return id as int but PUT as string SiteName string `json:"site_name"` // site_name is required always, also in PUT diff --git a/kentikapi/internal/api_payloads/tag.go b/kentikapi/internal/payloads/tag.go similarity index 98% rename from kentikapi/internal/api_payloads/tag.go rename to kentikapi/internal/payloads/tag.go index 597e5785..e9399b1f 100644 --- a/kentikapi/internal/api_payloads/tag.go +++ b/kentikapi/internal/payloads/tag.go @@ -1,4 +1,4 @@ -package api_payloads +package payloads import ( "time" @@ -102,6 +102,7 @@ func (p tagPayload) ToTag() *models.Tag { } // TagToPayload prepares POST/PUT request payload: fill only the user-provided fields. +//nolint:revive // tagPayLoad doesn't need to be exported func TagToPayload(u models.Tag) tagPayload { return tagPayload{ FlowTag: u.FlowTag, diff --git a/kentikapi/internal/api_payloads/tenant.go b/kentikapi/internal/payloads/tenant.go similarity index 99% rename from kentikapi/internal/api_payloads/tenant.go rename to kentikapi/internal/payloads/tenant.go index 187b9e06..a43734fc 100644 --- a/kentikapi/internal/api_payloads/tenant.go +++ b/kentikapi/internal/payloads/tenant.go @@ -1,4 +1,4 @@ -package api_payloads +package payloads import ( "time" diff --git a/kentikapi/internal/api_payloads/types.go b/kentikapi/internal/payloads/types.go similarity index 95% rename from kentikapi/internal/api_payloads/types.go rename to kentikapi/internal/payloads/types.go index 2ca8235c..aad06f68 100644 --- a/kentikapi/internal/api_payloads/types.go +++ b/kentikapi/internal/payloads/types.go @@ -1,4 +1,4 @@ -package api_payloads +package payloads import ( "encoding/json" @@ -53,11 +53,12 @@ func (p *BoolAsStringOrInt) UnmarshalJSON(data []byte) (err error) { *p = BoolAsStringOrInt(v) case int, float32, float64: asString := string(data) - if asString == "1" { + switch asString { + case "1": *p = true - } else if asString == "0" { + case "0": *p = false - } else { + default: return fmt.Errorf("BoolAsStringOrInt.UnmarshalJSON: parse bool unexpected value %v", value) } default: diff --git a/kentikapi/internal/api_payloads/types_test.go b/kentikapi/internal/payloads/types_test.go similarity index 59% rename from kentikapi/internal/api_payloads/types_test.go rename to kentikapi/internal/payloads/types_test.go index fb0c059b..15a9f6f7 100644 --- a/kentikapi/internal/api_payloads/types_test.go +++ b/kentikapi/internal/payloads/types_test.go @@ -1,45 +1,48 @@ -package api_payloads +package payloads_test import ( "encoding/json" "testing" + "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" "github.com/stretchr/testify/assert" ) func TestBoolAsString_UnmarshalJSON(t *testing.T) { + t.Parallel() + tests := []struct { input string - expectedResult BoolAsStringOrInt + expectedResult payloads.BoolAsStringOrInt expectedError bool }{ { input: `true`, - expectedResult: BoolAsStringOrInt(true), + expectedResult: payloads.BoolAsStringOrInt(true), }, { input: `false`, - expectedResult: BoolAsStringOrInt(false), + expectedResult: payloads.BoolAsStringOrInt(false), }, { input: `"true"`, - expectedResult: BoolAsStringOrInt(true), + expectedResult: payloads.BoolAsStringOrInt(true), }, { input: `"True"`, - expectedResult: BoolAsStringOrInt(true), + expectedResult: payloads.BoolAsStringOrInt(true), }, { input: `"false"`, - expectedResult: BoolAsStringOrInt(false), + expectedResult: payloads.BoolAsStringOrInt(false), }, { input: `"False"`, - expectedResult: BoolAsStringOrInt(false), + expectedResult: payloads.BoolAsStringOrInt(false), }, { input: `"invalid-string"`, expectedError: true, }, { input: `1`, - expectedResult: BoolAsStringOrInt(true), + expectedResult: payloads.BoolAsStringOrInt(true), }, { input: `0`, - expectedResult: BoolAsStringOrInt(false), + expectedResult: payloads.BoolAsStringOrInt(false), }, { input: `1.0`, expectedError: true, @@ -49,8 +52,11 @@ func TestBoolAsString_UnmarshalJSON(t *testing.T) { }, } for _, tt := range tests { + tt := tt t.Run(tt.input, func(t *testing.T) { - var result BoolAsStringOrInt + t.Parallel() + + var result payloads.BoolAsStringOrInt err := json.Unmarshal([]byte(tt.input), &result) if tt.expectedError { diff --git a/kentikapi/internal/api_payloads/user.go b/kentikapi/internal/payloads/user.go similarity index 96% rename from kentikapi/internal/api_payloads/user.go rename to kentikapi/internal/payloads/user.go index fed5a1d1..c2a5c233 100644 --- a/kentikapi/internal/api_payloads/user.go +++ b/kentikapi/internal/payloads/user.go @@ -1,4 +1,4 @@ -package api_payloads +package payloads import ( "time" @@ -72,6 +72,7 @@ func (p userPayload) ToUser() *models.User { } // UserToPayload prepares POST/PUT request payload: fill only the user-provided fields. +//nolint:revive // userPayLoad doesn't need to be exported func UserToPayload(u models.User) userPayload { return userPayload{ Username: u.Username, diff --git a/kentikapi/internal/resources/alerting.go b/kentikapi/internal/resources/alerting.go new file mode 100644 index 00000000..bbd736f8 --- /dev/null +++ b/kentikapi/internal/resources/alerting.go @@ -0,0 +1,63 @@ +package resources + +import ( + "context" + "errors" + + "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/endpoints" + "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" + "github.com/kentik/community_sdk_golang/kentikapi/models" +) + +type AlertingAPI struct { + BaseAPI +} + +// NewAlertingAPI is constructor. +func NewAlertingAPI(transport connection.Transport) *AlertingAPI { + return &AlertingAPI{ + BaseAPI{Transport: transport}, + } +} + +func (a *AlertingAPI) CreateManualMitigation(ctx context.Context, mm models.ManualMitigation) error { + payload := payloads.ManualMitigationToPayload(mm) + var response payloads.CreateManualMitigationResponse + + if err := a.PostAndValidate(ctx, endpoints.ManualMitigationPath, payload, &response); err != nil { + return err + } + + if response.Response.Result != "OK" { + return errors.New("creating Manual Mitigation failed") + } + + return nil +} + +func (a *AlertingAPI) GetActiveAlerts(ctx context.Context, params models.AlertsQueryParams) ([]models.Alarm, error) { + var response payloads.GetActiveAlertsResponse + + path := endpoints.GetActiveAlertsPath(params.StartTime, params.EndTime, params.FilterBy, params.FilterVal, + params.ShowMitigations, params.ShowAlarms, params.ShowMatches, params.LearningMode) + + if err := a.GetAndValidate(ctx, path, &response); err != nil { + return nil, err + } + + return response.ToAlarms(), nil +} + +func (a *AlertingAPI) GetAlertsHistory(ctx context.Context, + params models.AlertsQueryParams) ([]models.HistoricalAlert, error) { + var response payloads.GetHistoricalAlertsResponse + path := endpoints.GetAlertsHistoryPath(params.StartTime, params.EndTime, params.FilterBy, params.FilterVal, + params.SortOrder, params.ShowMitigations, params.ShowAlarms, params.ShowMatches, params.LearningMode) + + if err := a.GetAndValidate(ctx, path, &response); err != nil { + return nil, err + } + + return response.ToHistoricalAlerts(), nil +} diff --git a/kentikapi/internal/api_resources/alerting_test.go b/kentikapi/internal/resources/alerting_test.go similarity index 82% rename from kentikapi/internal/api_resources/alerting_test.go rename to kentikapi/internal/resources/alerting_test.go index 38439094..a8e59701 100644 --- a/kentikapi/internal/api_resources/alerting_test.go +++ b/kentikapi/internal/resources/alerting_test.go @@ -1,20 +1,25 @@ -package api_resources_test +package resources_test import ( "context" "testing" "time" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_resources" + "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/resources" "github.com/kentik/community_sdk_golang/kentikapi/models" "github.com/stretchr/testify/assert" ) -var time1 = time.Date(2020, time.January, 19, 13, 50, 0, 0, time.Local) -var time2 = time.Date(2021, time.March, 19, 13, 50, 0, 0, time.Local) +//nolint:gochecknoglobals +var ( + time1 = time.Date(2020, time.January, 19, 13, 50, 0, 0, time.Local) + time2 = time.Date(2021, time.March, 19, 13, 50, 0, 0, time.Local) +) func TestCrerateManualMitigation(t *testing.T) { + t.Parallel() + createResponsePayload := ` { "response": { @@ -23,8 +28,8 @@ func TestCrerateManualMitigation(t *testing.T) { }` expectedRequestBody := `{"ipCidr":"192.168.0.0/24","platformID":1234,"methodID":12345,"minutesBeforeAutoStop":"20"}` - transport := &api_connection.StubTransport{ResponseBody: createResponsePayload} - alertingAPI := api_resources.NewAlertingAPI(transport) + transport := &connection.StubTransport{ResponseBody: createResponsePayload} + alertingAPI := resources.NewAlertingAPI(transport) mm := models.ManualMitigation{ IPCidr: "192.168.0.0/24", PlatformID: 1234, @@ -39,6 +44,8 @@ func TestCrerateManualMitigation(t *testing.T) { } func TestGetActiveAlerts(t *testing.T) { + t.Parallel() + getResponsePayload := ` [ { @@ -76,8 +83,8 @@ func TestGetActiveAlerts(t *testing.T) { "alert_key_lookup": "443" } ]` - transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - alertingAPI := api_resources.NewAlertingAPI(transport) + transport := &connection.StubTransport{ResponseBody: getResponsePayload} + alertingAPI := resources.NewAlertingAPI(transport) alarmEndStr := "0000-00-00 00:00:00" expected := []models.Alarm{ @@ -127,10 +134,17 @@ func TestGetActiveAlerts(t *testing.T) { assert.Equal(t, expected, alerts) assert.NoError(t, err) - assert.Equal(t, "/alerts-active/alarms?endTime=2021-03-19T13%3A50%3A00&learningMode=0&showAlarms=1&showMatches=0&showMitigations=1&startTime=2020-01-19T13%3A50%3A00", transport.RequestPath) + assert.Equal( + t, + "/alerts-active/alarms?endTime=2021-03-19T13%3A50%3A00&learningMode=0&showAlarms=1&"+ + "showMatches=0&showMitigations=1&startTime=2020-01-19T13%3A50%3A00", + transport.RequestPath, + ) } func TestGetAlertsHistory(t *testing.T) { + t.Parallel() + getResponsePayload := ` [ { @@ -166,8 +180,8 @@ func TestGetAlertsHistory(t *testing.T) { "alert_key_lookup": "443" } ]` - transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - alertingAPI := api_resources.NewAlertingAPI(transport) + transport := &connection.StubTransport{ResponseBody: getResponsePayload} + alertingAPI := resources.NewAlertingAPI(transport) dateStr := "2021-01-19 13:50:00" expected := []models.HistoricalAlert{ @@ -216,5 +230,9 @@ func TestGetAlertsHistory(t *testing.T) { assert.Equal(t, expected, alerts) assert.NoError(t, err) - assert.Equal(t, "/alerts-active/alerts-history?endTime=2021-03-19T13%3A50%3A00&learningMode=0&showAlarms=1&showMatches=0&showMitigations=1&startTime=2020-01-19T13%3A50%3A00", transport.RequestPath) + assert.Equal( + t, "/alerts-active/alerts-history?endTime=2021-03-19T13%3A50%3A00&learningMode=0&"+ + "showAlarms=1&showMatches=0&showMitigations=1&startTime=2020-01-19T13%3A50%3A00", + transport.RequestPath, + ) } diff --git a/kentikapi/internal/api_resources/base.go b/kentikapi/internal/resources/base.go similarity index 88% rename from kentikapi/internal/api_resources/base.go rename to kentikapi/internal/resources/base.go index cb508afc..2dd4ada9 100644 --- a/kentikapi/internal/api_resources/base.go +++ b/kentikapi/internal/resources/base.go @@ -1,21 +1,21 @@ -package api_resources +package resources import ( "context" "encoding/json" "fmt" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" "github.com/kentik/community_sdk_golang/kentikapi/internal/validation" ) -// BaseAPI provides marshall/unmarshall + validation functionality for all resource APIs +// BaseAPI provides marshall/unmarshall + validation functionality for all resource APIs. type BaseAPI struct { - Transport api_connection.Transport + Transport connection.Transport } // GetAndValidate retrieves json at "url", unmarshalls and validates against required fields defined in struct tags of "output" -// output must be pointer to object or nil +// output must be pointer to object or nil. func (b BaseAPI) GetAndValidate(ctx context.Context, url string, output interface{}) error { responseBody, err := b.Transport.Get(ctx, url) if err != nil { @@ -39,7 +39,7 @@ func (b BaseAPI) GetAndValidate(ctx context.Context, url string, output interfac // PostAndValidate validates input against required fields defined in struct tags of "input", // retrieves json at "url", unmarshalls and validates against required fields in "output" -// output must be pointer to object or nil +// output must be pointer to object or nil. func (b BaseAPI) PostAndValidate(ctx context.Context, url string, input interface{}, output interface{}) error { if err := validation.CheckRequestRequiredFields("post", input); err != nil { return err @@ -72,7 +72,7 @@ func (b BaseAPI) PostAndValidate(ctx context.Context, url string, input interfac // UpdateAndValidate validates input against required fields defined in struct tags of "input", // retrieves json at "url", unmarshalls and validates against required fields in "output" -// output must be pointer to object or nil +// output must be pointer to object or nil. func (b BaseAPI) UpdateAndValidate(ctx context.Context, url string, input interface{}, output interface{}) error { if err := validation.CheckRequestRequiredFields("put", input); err != nil { return err @@ -103,8 +103,9 @@ func (b BaseAPI) UpdateAndValidate(ctx context.Context, url string, input interf return nil } -// DeleteAndValidate retrieves json at "url" unmarshalls and validates against required fields defined in struct tags of "output" -// output must be pointer to object or nil +// DeleteAndValidate retrieves json at "url" unmarshalls and validates +// against required fields defined in struct tags of "output" +// output must be pointer to object or nil. func (b BaseAPI) DeleteAndValidate(ctx context.Context, url string, output interface{}) error { responseBody, err := b.Transport.Delete(ctx, url) if err != nil { diff --git a/kentikapi/internal/resources/custom_applications.go b/kentikapi/internal/resources/custom_applications.go new file mode 100644 index 00000000..559caf7a --- /dev/null +++ b/kentikapi/internal/resources/custom_applications.go @@ -0,0 +1,64 @@ +package resources + +import ( + "context" + + "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/endpoints" + "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" + "github.com/kentik/community_sdk_golang/kentikapi/models" +) + +type CustomApplicationsAPI struct { + BaseAPI +} + +// NewCustomApplicationsAPI is constructor. +func NewCustomApplicationsAPI(transport connection.Transport) *CustomApplicationsAPI { + return &CustomApplicationsAPI{ + BaseAPI{Transport: transport}, + } +} + +// GetAll custom applications. +func (a *CustomApplicationsAPI) GetAll(ctx context.Context) ([]models.CustomApplication, error) { + var response payloads.GetAllCustomApplicationsResponse + if err := a.GetAndValidate(ctx, endpoints.GetAllCustomApplications(), &response); err != nil { + return []models.CustomApplication{}, err + } + + return response.ToCustomApplications() +} + +// Create new custom application. +func (a *CustomApplicationsAPI) Create(ctx context.Context, + customApplication models.CustomApplication) (*models.CustomApplication, error) { + payload := payloads.CustomApplicationToPayload(customApplication) + request := payloads.CreateCustomApplicationRequest(payload) + var response payloads.CreateCustomApplicationResponse + if err := a.PostAndValidate(ctx, endpoints.CreateCustomApplication(), request, &response); err != nil { + return nil, err + } + + result, err := response.ToCustomApplication() + return &result, err +} + +// Update custom application. +func (a *CustomApplicationsAPI) Update(ctx context.Context, + customApplication models.CustomApplication) (*models.CustomApplication, error) { + payload := payloads.CustomApplicationToPayload(customApplication) + request := payloads.UpdateCustomApplicationRequest(payload) + var response payloads.UpdateCustomApplicationResponse + if err := a.UpdateAndValidate(ctx, endpoints.UpdateCustomApplication(customApplication.ID), request, &response); err != nil { + return nil, err + } + + result, err := response.ToCustomApplication() + return &result, err +} + +// Delete custom application. +func (a *CustomApplicationsAPI) Delete(ctx context.Context, id models.ID) error { + return a.DeleteAndValidate(ctx, endpoints.DeleteCustomApplication(id), nil) +} diff --git a/kentikapi/internal/api_resources/custom_applications_test.go b/kentikapi/internal/resources/custom_applications_test.go similarity index 88% rename from kentikapi/internal/api_resources/custom_applications_test.go rename to kentikapi/internal/resources/custom_applications_test.go index 61062db9..1457aee6 100644 --- a/kentikapi/internal/api_resources/custom_applications_test.go +++ b/kentikapi/internal/resources/custom_applications_test.go @@ -1,4 +1,4 @@ -package api_resources_test +package resources_test import ( "context" @@ -6,8 +6,8 @@ import ( "testing" "time" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_resources" + "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/resources" "github.com/kentik/community_sdk_golang/kentikapi/internal/utils" "github.com/kentik/community_sdk_golang/kentikapi/models" "github.com/stretchr/testify/assert" @@ -15,6 +15,8 @@ import ( ) func TestGetAll(t *testing.T) { + t.Parallel() + getResponsePayload := ` [ { @@ -44,8 +46,8 @@ func TestGetAll(t *testing.T) { "edate": "2020-12-11T07:08:20.968Z" } ]` - transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - applicationsAPI := api_resources.NewCustomApplicationsAPI(transport) + transport := &connection.StubTransport{ResponseBody: getResponsePayload} + applicationsAPI := resources.NewCustomApplicationsAPI(transport) // act applications, err := applicationsAPI.GetAll(context.Background()) @@ -76,6 +78,8 @@ func TestGetAll(t *testing.T) { } func TestCreateCustomApplication(t *testing.T) { + t.Parallel() + createResponsePayload := ` { "name": "apitest-customapp-1", @@ -88,8 +92,8 @@ func TestCreateCustomApplication(t *testing.T) { "user_id": "144319", "company_id": "74333" }` - transport := &api_connection.StubTransport{ResponseBody: createResponsePayload} - applicationsAPI := api_resources.NewCustomApplicationsAPI(transport) + transport := &connection.StubTransport{ResponseBody: createResponsePayload} + applicationsAPI := resources.NewCustomApplicationsAPI(transport) app := models.NewCustomApplication("apitest-customapp-1") models.SetOptional(&app.Description, "Testing custom application api") @@ -130,6 +134,8 @@ func TestCreateCustomApplication(t *testing.T) { } func TestUpdateCustomApplication(t *testing.T) { + t.Parallel() + updateResponsePayload := ` { "id": 207, @@ -144,8 +150,8 @@ func TestUpdateCustomApplication(t *testing.T) { "cdate": "2020-12-11T07:07:20.968Z", "edate": "2020-12-11T07:07:20.968Z" }` - transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} - applicationsAPI := api_resources.NewCustomApplicationsAPI(transport) + transport := &connection.StubTransport{ResponseBody: updateResponsePayload} + applicationsAPI := resources.NewCustomApplicationsAPI(transport) appID := models.ID(207) app := models.CustomApplication{ @@ -188,10 +194,12 @@ func TestUpdateCustomApplication(t *testing.T) { } func TestDeleteCustomApplication(t *testing.T) { + t.Parallel() + // arrange deleteResponsePayload := "" // deleting custom application responds with empty body - transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} - appliationsAPI := api_resources.NewCustomApplicationsAPI(transport) + transport := &connection.StubTransport{ResponseBody: deleteResponsePayload} + appliationsAPI := resources.NewCustomApplicationsAPI(transport) // act appID := models.ID(42) diff --git a/kentikapi/internal/resources/custom_dimensions.go b/kentikapi/internal/resources/custom_dimensions.go new file mode 100644 index 00000000..5c1684e8 --- /dev/null +++ b/kentikapi/internal/resources/custom_dimensions.go @@ -0,0 +1,119 @@ +package resources + +import ( + "context" + + "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/endpoints" + "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" + "github.com/kentik/community_sdk_golang/kentikapi/models" +) + +type CustomDimensionsAPI struct { + BaseAPI + Populators *populatorsAPI +} + +// NewCustomDimensionsAPI is constructor. +func NewCustomDimensionsAPI(transport connection.Transport) *CustomDimensionsAPI { + return &CustomDimensionsAPI{ + BaseAPI{Transport: transport}, + &populatorsAPI{BaseAPI{Transport: transport}}, + } +} + +// GetAll custom dimensions. +func (a *CustomDimensionsAPI) GetAll(ctx context.Context) ([]models.CustomDimension, error) { + var response payloads.GetAllCustomDimensionsResponse + if err := a.GetAndValidate(ctx, endpoints.GetAllCustomDimensions(), &response); err != nil { + return []models.CustomDimension{}, err + } + + return response.ToCustomDimensions(), nil +} + +// Get custom dimension with given ID. +func (a *CustomDimensionsAPI) Get(ctx context.Context, id models.ID) (*models.CustomDimension, error) { + var response payloads.GetCustomDimensionResponse + if err := a.GetAndValidate(ctx, endpoints.GetCustomDimension(id), &response); err != nil { + return nil, err + } + + result := response.ToCustomDimension() + return &result, nil +} + +// Create new custom dimension. +func (a *CustomDimensionsAPI) Create(ctx context.Context, + customDimension models.CustomDimension) (*models.CustomDimension, error) { + payload := payloads.CustomDimensionToPayload(customDimension) + + request := payloads.CreateCustomDimensionRequest(payload) + var response payloads.CreateCustomDimensionResponse + if err := a.PostAndValidate(ctx, endpoints.CreateCustomDimension(), request, &response); err != nil { + return nil, err + } + + result := response.ToCustomDimension() + return &result, nil +} + +// Update custom dimension. +func (a *CustomDimensionsAPI) Update(ctx context.Context, + customDimension models.CustomDimension) (*models.CustomDimension, error) { + payload := payloads.CustomDimensionToPayload(customDimension) + + request := payloads.UpdateCustomDimensionRequest(payload) + var response payloads.UpdateCustomDimensionResponse + if err := a.UpdateAndValidate(ctx, endpoints.UpdateCustomDimension(customDimension.ID), request, &response); err != nil { + return nil, err + } + + result := response.ToCustomDimension() + return &result, nil +} + +// Delete custom dimension. +func (a *CustomDimensionsAPI) Delete(ctx context.Context, id models.ID) error { + return a.DeleteAndValidate(ctx, endpoints.DeleteCustomDimension(id), nil) +} + +type populatorsAPI struct { + BaseAPI +} + +// Create new populator. +func (a *populatorsAPI) Create(ctx context.Context, populator models.Populator) (*models.Populator, error) { + payload := payloads.PopulatorToPayload(populator) + + request := payloads.CreatePopulatorRequest{Payload: payload} + var response payloads.CreatePopulatorResponse + if err := a.PostAndValidate(ctx, endpoints.CreatePopulator(populator.DimensionID), request, &response); err != nil { + return nil, err + } + + result := response.ToPopulator() + return &result, nil +} + +// Update populator. +func (a *populatorsAPI) Update(ctx context.Context, populator models.Populator) (*models.Populator, error) { + payload := payloads.PopulatorToPayload(populator) + + request := payloads.UpdatePopulatorRequest{Payload: payload} + var response payloads.UpdatePopulatorResponse + if err := a.UpdateAndValidate(ctx, + endpoints.UpdatePopulator(populator.DimensionID, populator.ID), + request, + &response); err != nil { + return nil, err + } + + result := response.ToPopulator() + return &result, nil +} + +// Delete populator. +func (a *populatorsAPI) Delete(ctx context.Context, dimensionID, populatorID models.ID) error { + return a.DeleteAndValidate(ctx, endpoints.DeletePopulator(dimensionID, populatorID), nil) +} diff --git a/kentikapi/internal/api_resources/custom_dimensions_test.go b/kentikapi/internal/resources/custom_dimensions_test.go similarity index 92% rename from kentikapi/internal/api_resources/custom_dimensions_test.go rename to kentikapi/internal/resources/custom_dimensions_test.go index 2ac60550..0013777a 100644 --- a/kentikapi/internal/api_resources/custom_dimensions_test.go +++ b/kentikapi/internal/resources/custom_dimensions_test.go @@ -1,4 +1,4 @@ -package api_resources_test +package resources_test import ( "context" @@ -7,8 +7,8 @@ import ( "testing" "time" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_resources" + "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/resources" "github.com/kentik/community_sdk_golang/kentikapi/internal/testutil" "github.com/kentik/community_sdk_golang/kentikapi/internal/utils" "github.com/kentik/community_sdk_golang/kentikapi/models" @@ -17,6 +17,8 @@ import ( ) func TestCreateCustomDimension(t *testing.T) { + t.Parallel() + // arrange createResponsePayload := ` { @@ -29,9 +31,13 @@ func TestCreateCustomDimension(t *testing.T) { "populators": [] } }` - transport := &api_connection.StubTransport{ResponseBody: createResponsePayload} - customDimensionsAPI := api_resources.NewCustomDimensionsAPI(transport) - dimension := models.NewCustomDimension("c_testapi_dimension_1", "dimension_display_name", models.CustomDimensionTypeStr) + transport := &connection.StubTransport{ResponseBody: createResponsePayload} + customDimensionsAPI := resources.NewCustomDimensionsAPI(transport) + dimension := models.NewCustomDimension( + "c_testapi_dimension_1", + "dimension_display_name", + models.CustomDimensionTypeStr, + ) // act created, err := customDimensionsAPI.Create(context.Background(), *dimension) @@ -58,6 +64,8 @@ func TestCreateCustomDimension(t *testing.T) { } func TestUpdateCustomDimension(t *testing.T) { + t.Parallel() + // arrange updateResponsePayload := ` { @@ -70,8 +78,8 @@ func TestUpdateCustomDimension(t *testing.T) { "populators": [] } }` - transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} - customDimensionsAPI := api_resources.NewCustomDimensionsAPI(transport) + transport := &connection.StubTransport{ResponseBody: updateResponsePayload} + customDimensionsAPI := resources.NewCustomDimensionsAPI(transport) dimensionID := models.ID(42) dimension := models.CustomDimension{ID: dimensionID, DisplayName: "dimension_display_name2"} @@ -98,6 +106,8 @@ func TestUpdateCustomDimension(t *testing.T) { } func TestGetCustomDimension(t *testing.T) { + t.Parallel() + tests := []struct { name string transportError error @@ -307,10 +317,13 @@ func TestGetCustomDimension(t *testing.T) { }, } for _, tt := range tests { + tt := tt t.Run(tt.name, func(t *testing.T) { + t.Parallel() + // arrange - transport := &api_connection.StubTransport{ResponseBody: tt.responseBody} - customDimensionsAPI := api_resources.NewCustomDimensionsAPI(transport) + transport := &connection.StubTransport{ResponseBody: tt.responseBody} + customDimensionsAPI := resources.NewCustomDimensionsAPI(transport) dimensionID := 42 // act @@ -333,6 +346,8 @@ func TestGetCustomDimension(t *testing.T) { } func TestGetAllCustomDimensions(t *testing.T) { + t.Parallel() + // arrange getResponsePayload := ` { @@ -371,8 +386,8 @@ func TestGetAllCustomDimensions(t *testing.T) { } ] }` - transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - customDimensionsAPI := api_resources.NewCustomDimensionsAPI(transport) + transport := &connection.StubTransport{ResponseBody: getResponsePayload} + customDimensionsAPI := resources.NewCustomDimensionsAPI(transport) // act dimensions, err := customDimensionsAPI.GetAll(context.Background()) @@ -416,10 +431,12 @@ func TestGetAllCustomDimensions(t *testing.T) { } func TestDeleteCustomDimension(t *testing.T) { + t.Parallel() + // arrange deleteResponsePayload := "" // deleting device responds with empty body - transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} - customDimensionsAPI := api_resources.NewCustomDimensionsAPI(transport) + transport := &connection.StubTransport{ResponseBody: deleteResponsePayload} + customDimensionsAPI := resources.NewCustomDimensionsAPI(transport) // act dimensionID := models.ID(42) @@ -435,6 +452,8 @@ func TestDeleteCustomDimension(t *testing.T) { } func TestCreatePopulator(t *testing.T) { + t.Parallel() + // arrange createResponsePayload := ` { @@ -469,10 +488,15 @@ func TestCreatePopulator(t *testing.T) { "updated_date": "2020-12-15T07:55:23.0Z" } }` - transport := &api_connection.StubTransport{ResponseBody: createResponsePayload} - customDimensionsAPI := api_resources.NewCustomDimensionsAPI(transport) + transport := &connection.StubTransport{ResponseBody: createResponsePayload} + customDimensionsAPI := resources.NewCustomDimensionsAPI(transport) dimensionID := models.ID(24001) - populator := models.NewPopulator(dimensionID, "testapi-dimension-value-1", "device1,128.0.0.100", models.PopulatorDirectionDst) + populator := models.NewPopulator( + dimensionID, + "testapi-dimension-value-1", + "device1,128.0.0.100", + models.PopulatorDirectionDst, + ) models.SetOptional(&populator.InterfaceName, "interface1,interface2") models.SetOptional(&populator.Addr, "128.0.0.1/32,128.0.0.2/32") models.SetOptional(&populator.Port, "1001,1002") @@ -556,6 +580,8 @@ func TestCreatePopulator(t *testing.T) { } func TestUpdatePopulator(t *testing.T) { + t.Parallel() + // arrange updateResponsePayload := ` { @@ -578,8 +604,8 @@ func TestUpdatePopulator(t *testing.T) { } }` - transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} - customDimensionsAPI := api_resources.NewCustomDimensionsAPI(transport) + transport := &connection.StubTransport{ResponseBody: updateResponsePayload} + customDimensionsAPI := resources.NewCustomDimensionsAPI(transport) dimensionID := models.ID(24001) populatorID := models.ID(1510862280) @@ -634,10 +660,12 @@ func TestUpdatePopulator(t *testing.T) { } func TestDeletePopulator(t *testing.T) { + t.Parallel() + // arrange deleteResponsePayload := "" // deleting device responds with empty body - transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} - customDimensionsAPI := api_resources.NewCustomDimensionsAPI(transport) + transport := &connection.StubTransport{ResponseBody: deleteResponsePayload} + customDimensionsAPI := resources.NewCustomDimensionsAPI(transport) // act dimensionID := models.ID(42) diff --git a/kentikapi/internal/resources/device_labels.go b/kentikapi/internal/resources/device_labels.go new file mode 100644 index 00000000..ca2aef85 --- /dev/null +++ b/kentikapi/internal/resources/device_labels.go @@ -0,0 +1,85 @@ +package resources + +import ( + "context" + "fmt" + + "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/endpoints" + "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" + "github.com/kentik/community_sdk_golang/kentikapi/models" +) + +type DeviceLabelsAPI struct { + BaseAPI +} + +// NewDeviceLabelsAPI is constructor. +func NewDeviceLabelsAPI(transport connection.Transport) *DeviceLabelsAPI { + return &DeviceLabelsAPI{ + BaseAPI{Transport: transport}, + } +} + +// GetAll labels. +func (a *DeviceLabelsAPI) GetAll(ctx context.Context) ([]models.DeviceLabel, error) { + var response payloads.GetAllDeviceLabelsResponse + if err := a.GetAndValidate(ctx, endpoints.GetAllLabels(), &response); err != nil { + return []models.DeviceLabel{}, err + } + + return response.ToDeviceLabels() +} + +// Get label with given ID. +func (a *DeviceLabelsAPI) Get(ctx context.Context, id models.ID) (*models.DeviceLabel, error) { + var response payloads.GetDeviceLabelResponse + if err := a.GetAndValidate(ctx, endpoints.GetLabel(id), &response); err != nil { + return nil, err + } + + device, err := response.ToDeviceLabel() + return &device, err +} + +// Create new label. +func (a *DeviceLabelsAPI) Create(ctx context.Context, label models.DeviceLabel) (*models.DeviceLabel, error) { + payload := payloads.DeviceLabelToPayload(label) + + request := payloads.CreateDeviceLabelRequest(payload) + var response payloads.CreateDeviceLabelResponse + if err := a.PostAndValidate(ctx, endpoints.CreateLabel(), request, &response); err != nil { + return nil, err + } + + result, err := response.ToDeviceLabel() + return &result, err +} + +// Update label. +func (a *DeviceLabelsAPI) Update(ctx context.Context, label models.DeviceLabel) (*models.DeviceLabel, error) { + payload := payloads.DeviceLabelToPayload(label) + + request := payloads.UpdateDeviceLabelRequest(payload) + var response payloads.UpdateDeviceLabelResponse + if err := a.UpdateAndValidate(ctx, endpoints.UpdateLabel(label.ID), request, &response); err != nil { + return nil, err + } + + result, err := response.ToDeviceLabel() + return &result, err +} + +// Delete label. +func (a *DeviceLabelsAPI) Delete(ctx context.Context, id models.ID) error { + var response payloads.DeleteDeviceLabelResponse + if err := a.DeleteAndValidate(ctx, endpoints.DeleteLabel(id), &response); err != nil { + return err + } + + if !response.Success { + return fmt.Errorf("DeviceLabelsAPI.Delete: API returned success=false for id=%v", id) + } + + return nil +} diff --git a/kentikapi/internal/api_resources/device_labels_test.go b/kentikapi/internal/resources/device_labels_test.go similarity index 89% rename from kentikapi/internal/api_resources/device_labels_test.go rename to kentikapi/internal/resources/device_labels_test.go index 121d4ec1..00f36b3f 100644 --- a/kentikapi/internal/api_resources/device_labels_test.go +++ b/kentikapi/internal/resources/device_labels_test.go @@ -1,4 +1,4 @@ -package api_resources_test +package resources_test import ( "context" @@ -6,8 +6,8 @@ import ( "testing" "time" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_resources" + "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/resources" "github.com/kentik/community_sdk_golang/kentikapi/internal/utils" "github.com/kentik/community_sdk_golang/kentikapi/models" "github.com/stretchr/testify/assert" @@ -15,6 +15,8 @@ import ( ) func TestCreateDeviceLabel(t *testing.T) { + t.Parallel() + // arrange createResponsePayload := ` { @@ -28,8 +30,8 @@ func TestCreateDeviceLabel(t *testing.T) { "created_date": "2018-05-16T20:21:10.406Z", "updated_date": "2018-05-16T20:21:10.406Z" }` - transport := &api_connection.StubTransport{ResponseBody: createResponsePayload} - labelsAPI := api_resources.NewDeviceLabelsAPI(transport) + transport := &connection.StubTransport{ResponseBody: createResponsePayload} + labelsAPI := resources.NewDeviceLabelsAPI(transport) label := models.NewDeviceLabel("apitest-device_label-1", "#00FF00") // act @@ -57,6 +59,8 @@ func TestCreateDeviceLabel(t *testing.T) { } func TestUpdateDeviceLabel(t *testing.T) { + t.Parallel() + // arrange updateResponsePayload := ` { @@ -69,8 +73,8 @@ func TestUpdateDeviceLabel(t *testing.T) { "created_date": "2018-05-16T20:21:10.406Z", "updated_date": "2018-06-16T20:21:10.406Z" }` - transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} - labelsAPI := api_resources.NewDeviceLabelsAPI(transport) + transport := &connection.StubTransport{ResponseBody: updateResponsePayload} + labelsAPI := resources.NewDeviceLabelsAPI(transport) label := models.DeviceLabel{Name: "apitest-device_label-one", Color: "#AA00FF"} label.ID = models.ID(42) @@ -99,6 +103,8 @@ func TestUpdateDeviceLabel(t *testing.T) { } func TestGetLabel(t *testing.T) { + t.Parallel() + // arrange getResponsePayload := ` { @@ -118,8 +124,8 @@ func TestGetLabel(t *testing.T) { "created_date": "2018-05-16T20:21:10.406Z", "updated_date": "2018-05-16T20:21:10.406Z" }` - transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - labelsAPI := api_resources.NewDeviceLabelsAPI(transport) + transport := &connection.StubTransport{ResponseBody: getResponsePayload} + labelsAPI := resources.NewDeviceLabelsAPI(transport) labelID := models.ID(32) // act @@ -149,6 +155,8 @@ func TestGetLabel(t *testing.T) { } func TestGetAllLabels(t *testing.T) { + t.Parallel() + // arrange getResponsePayload := ` [ @@ -186,8 +194,8 @@ func TestGetAllLabels(t *testing.T) { "updated_date": "2020-11-20T13:45:27.430Z" } ]` - transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - labelsAPI := api_resources.NewDeviceLabelsAPI(transport) + transport := &connection.StubTransport{ResponseBody: getResponsePayload} + labelsAPI := resources.NewDeviceLabelsAPI(transport) // act labels, err := labelsAPI.GetAll(context.Background()) @@ -228,13 +236,15 @@ func TestGetAllLabels(t *testing.T) { } func TestDeleteDeviceLabel(t *testing.T) { + t.Parallel() + // arrange deleteResponsePayload := ` { "success": true }` - transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} - labelsAPI := api_resources.NewDeviceLabelsAPI(transport) + transport := &connection.StubTransport{ResponseBody: deleteResponsePayload} + labelsAPI := resources.NewDeviceLabelsAPI(transport) // act labelID := models.ID(42) diff --git a/kentikapi/internal/resources/devices.go b/kentikapi/internal/resources/devices.go new file mode 100644 index 00000000..bf0f6463 --- /dev/null +++ b/kentikapi/internal/resources/devices.go @@ -0,0 +1,152 @@ +package resources + +import ( + "context" + + "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/endpoints" + "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" + "github.com/kentik/community_sdk_golang/kentikapi/models" +) + +type DevicesAPI struct { + BaseAPI + Interfaces *interfacesAPI +} + +// NewDevicesAPI is constructor. +func NewDevicesAPI(transport connection.Transport) *DevicesAPI { + return &DevicesAPI{ + BaseAPI{Transport: transport}, + &interfacesAPI{BaseAPI{Transport: transport}}, + } +} + +// GetAll devices. +func (a *DevicesAPI) GetAll(ctx context.Context) ([]models.Device, error) { + var response payloads.GetAllDevicesResponse + if err := a.GetAndValidate(ctx, endpoints.DevicesPath, &response); err != nil { + return []models.Device{}, err + } + + return response.ToDevices() +} + +// Get device with given ID. +func (a *DevicesAPI) Get(ctx context.Context, id models.ID) (*models.Device, error) { + var response payloads.GetDeviceResponse + if err := a.GetAndValidate(ctx, endpoints.GetDevice(id), &response); err != nil { + return nil, err + } + + device, err := response.ToDevice() + return &device, err +} + +// Create new device. +func (a *DevicesAPI) Create(ctx context.Context, device models.Device) (*models.Device, error) { + request := payloads.CreateDeviceRequest{Payload: payloads.DeviceToPayload(device)} + var response payloads.CreateDeviceResponse + if err := a.PostAndValidate(ctx, endpoints.DevicePath, request, &response); err != nil { + return nil, err + } + + result, err := response.ToDevice() + return &result, err +} + +// Update device. +func (a *DevicesAPI) Update(ctx context.Context, device models.Device) (*models.Device, error) { + request := payloads.UpdateDeviceRequest{Payload: payloads.DeviceToPayload(device)} + var response payloads.UpdateDeviceResponse + if err := a.UpdateAndValidate(ctx, endpoints.UpdateDevice(device.ID), request, &response); err != nil { + return nil, err + } + + result, err := response.ToDevice() + return &result, err +} + +// Delete device +// Note: KentikAPI requires sending delete request twice to actually delete the device. +// This is a safety measure preventing deletion by mistake. +func (a *DevicesAPI) Delete(ctx context.Context, id models.ID) error { + return a.DeleteAndValidate(ctx, endpoints.GetDevice(id), nil) +} + +// ApplyLabels assigns labels to given device. +func (a *DevicesAPI) ApplyLabels(ctx context.Context, deviceID models.ID, labels []models.ID) (models.AppliedLabels, error) { + payload := payloads.LabelIDsToPayload(labels) + + request := payloads.ApplyLabelsRequest{Labels: payload} + var response payloads.ApplyLabelsResponse + if err := a.UpdateAndValidate(ctx, endpoints.ApplyDeviceLabels(deviceID), request, &response); err != nil { + return models.AppliedLabels{}, err + } + + return response.ToAppliedLabels() +} + +type interfacesAPI struct { + BaseAPI +} + +// GetAll interfaces of given device. +func (a *interfacesAPI) GetAll(ctx context.Context, deviceID models.ID) ([]models.Interface, error) { + var response payloads.GetAllInterfacesResponse + if err := a.GetAndValidate(ctx, endpoints.GetAllInterfaces(deviceID), &response); err != nil { + return nil, err + } + + return response.ToInterfaces() +} + +// Get interface of given device with given ID. +func (a *interfacesAPI) Get(ctx context.Context, deviceID, interfaceID models.ID) (*models.Interface, error) { + var response payloads.GetInterfaceResponse + if err := a.GetAndValidate(ctx, endpoints.GetInterface(deviceID, interfaceID), &response); err != nil { + return nil, err + } + + intf, err := response.ToInterface() + return &intf, err +} + +// Create new interface under given device. +func (a *interfacesAPI) Create(ctx context.Context, intf models.Interface) (*models.Interface, error) { + payload, err := payloads.InterfaceToPayload(intf) + if err != nil { + return nil, err + } + + request := payloads.CreateInterfaceRequest(payload) + var response payloads.CreateInterfaceResponse + if err = a.PostAndValidate(ctx, endpoints.CreateInterface(intf.DeviceID), request, &response); err != nil { + return nil, err + } + + result, err := response.ToInterface() + return &result, err +} + +// Delete interface. +func (a *interfacesAPI) Delete(ctx context.Context, deviceID, interfaceID models.ID) error { + return a.DeleteAndValidate(ctx, endpoints.DeleteInterface(deviceID, interfaceID), nil) +} + +// Update interface. +func (a *interfacesAPI) Update(ctx context.Context, intf models.Interface) (*models.Interface, error) { + payload, err := payloads.InterfaceToPayload(intf) + if err != nil { + return nil, err + } + + request := payloads.UpdateInterfaceRequest(payload) + var response payloads.UpdateInterfaceResponse + if err = a.UpdateAndValidate(ctx, endpoints.UpdateInterface(intf.DeviceID, intf.ID), request, &response); err != nil { + return nil, err + } + + result, err := response.ToInterface() + return &result, err +} diff --git a/kentikapi/internal/api_resources/devices_test.go b/kentikapi/internal/resources/devices_test.go similarity index 95% rename from kentikapi/internal/api_resources/devices_test.go rename to kentikapi/internal/resources/devices_test.go index bb6d5603..cd449454 100644 --- a/kentikapi/internal/api_resources/devices_test.go +++ b/kentikapi/internal/resources/devices_test.go @@ -1,4 +1,5 @@ -package api_resources_test +//nolint:dupl +package resources_test import ( "context" @@ -7,8 +8,8 @@ import ( "testing" "time" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_resources" + "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/resources" "github.com/kentik/community_sdk_golang/kentikapi/internal/testutil" "github.com/kentik/community_sdk_golang/kentikapi/internal/utils" "github.com/kentik/community_sdk_golang/kentikapi/models" @@ -17,6 +18,8 @@ import ( ) func TestCreateDeviceRouter(t *testing.T) { + t.Parallel() + // arrange createResponsePayload := ` { @@ -94,8 +97,8 @@ func TestCreateDeviceRouter(t *testing.T) { "device_subtype": "router" } }` - transport := &api_connection.StubTransport{ResponseBody: createResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + transport := &connection.StubTransport{ResponseBody: createResponsePayload} + devicesAPI := resources.NewDevicesAPI(transport) // act snmpv3conf := models.NewSNMPv3Conf("John") @@ -209,6 +212,8 @@ func TestCreateDeviceRouter(t *testing.T) { } func TestCreateDeviceDNS(t *testing.T) { + t.Parallel() + // arrange createResponsePayload := ` { @@ -275,8 +280,8 @@ func TestCreateDeviceDNS(t *testing.T) { "device_subtype": "aws_subnet" } }` - transport := &api_connection.StubTransport{ResponseBody: createResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + transport := &connection.StubTransport{ResponseBody: createResponsePayload} + devicesAPI := resources.NewDevicesAPI(transport) // act dns := models.NewDeviceDNS( @@ -360,6 +365,8 @@ func TestCreateDeviceDNS(t *testing.T) { } func TestUpdatetDeviceRouter(t *testing.T) { + t.Parallel() + // arrange updateResponsePayload := ` { @@ -438,8 +445,8 @@ func TestUpdatetDeviceRouter(t *testing.T) { "device_subtype": "paloalto" } }` - transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + transport := &connection.StubTransport{ResponseBody: updateResponsePayload} + devicesAPI := resources.NewDevicesAPI(transport) // act snmpv3conf := models.NewSNMPv3Conf("John") @@ -555,6 +562,8 @@ func TestUpdatetDeviceRouter(t *testing.T) { } func TestGetDevice(t *testing.T) { + t.Parallel() + tests := []struct { name string transportError error @@ -800,8 +809,8 @@ func TestGetDevice(t *testing.T) { ID: 2590, UserID: testutil.IDPtr(133210), CompanyID: 74333, - CreatedDate: time.Date(2020, 10, 5, 15, 28, 00, 276*1000000, time.UTC), - UpdatedDate: time.Date(2020, 10, 5, 15, 28, 00, 276*1000000, time.UTC), + CreatedDate: time.Date(2020, 10, 5, 15, 28, 0, 276*1000000, time.UTC), + UpdatedDate: time.Date(2020, 10, 5, 15, 28, 0, 276*1000000, time.UTC), }, { Name: "GCP: traffic-generator-gcp", @@ -1079,10 +1088,13 @@ func TestGetDevice(t *testing.T) { }, } for _, tt := range tests { + tt := tt t.Run(tt.name, func(t *testing.T) { + t.Parallel() + // arrange - transport := &api_connection.StubTransport{ResponseBody: tt.responseBody} - devicesAPI := api_resources.NewDevicesAPI(transport) + transport := &connection.StubTransport{ResponseBody: tt.responseBody} + devicesAPI := resources.NewDevicesAPI(transport) deviceID := 43 // act @@ -1105,6 +1117,8 @@ func TestGetDevice(t *testing.T) { } func TestGetAllDevices(t *testing.T) { + t.Parallel() + // arrange getResponsePayload := ` { @@ -1276,8 +1290,8 @@ func TestGetAllDevices(t *testing.T) { } ] }` - transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + transport := &connection.StubTransport{ResponseBody: getResponsePayload} + devicesAPI := resources.NewDevicesAPI(transport) // act devices, err := devicesAPI.GetAll(context.Background()) @@ -1325,8 +1339,8 @@ func TestGetAllDevices(t *testing.T) { assert.Equal(2, len(device.Labels)) assert.Equal(models.ID(2590), device.Labels[0].ID) assert.Equal("AWS: terraform-demo-aws", device.Labels[0].Name) - assert.Equal(time.Date(2020, 10, 5, 15, 28, 00, 276*1000000, time.UTC), device.Labels[0].UpdatedDate) - assert.Equal(time.Date(2020, 10, 5, 15, 28, 00, 276*1000000, time.UTC), device.Labels[0].CreatedDate) + assert.Equal(time.Date(2020, 10, 5, 15, 28, 0, 276*1000000, time.UTC), device.Labels[0].UpdatedDate) + assert.Equal(time.Date(2020, 10, 5, 15, 28, 0, 276*1000000, time.UTC), device.Labels[0].CreatedDate) assert.Equal(models.ID(133210), *device.Labels[0].UserID) assert.Equal(models.ID(74333), device.Labels[0].CompanyID) assert.Equal("#5340A5", device.Labels[0].Color) @@ -1375,10 +1389,12 @@ func TestGetAllDevices(t *testing.T) { } func TestDeleteDevice(t *testing.T) { + t.Parallel() + // arrange deleteResponsePayload := "" // deleting device responds with empty body - transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + transport := &connection.StubTransport{ResponseBody: deleteResponsePayload} + devicesAPI := resources.NewDevicesAPI(transport) // act deviceID := models.ID(42) @@ -1394,6 +1410,8 @@ func TestDeleteDevice(t *testing.T) { } func TestApplyLabels(t *testing.T) { + t.Parallel() + // arrange applyLabelsResponsePayload := ` { @@ -1428,8 +1446,8 @@ func TestApplyLabels(t *testing.T) { } ] }` - transport := &api_connection.StubTransport{ResponseBody: applyLabelsResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + transport := &connection.StubTransport{ResponseBody: applyLabelsResponsePayload} + devicesAPI := resources.NewDevicesAPI(transport) // act deviceID := models.ID(42) @@ -1470,6 +1488,8 @@ func TestApplyLabels(t *testing.T) { } func TestGetInterfaceMinimal(t *testing.T) { + t.Parallel() + // arrange getResponsePayload := ` { @@ -1497,8 +1517,8 @@ func TestGetInterfaceMinimal(t *testing.T) { "secondary_ips": null } }` - transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + transport := &connection.StubTransport{ResponseBody: getResponsePayload} + devicesAPI := resources.NewDevicesAPI(transport) // act deviceID := models.ID(42) @@ -1537,6 +1557,8 @@ func TestGetInterfaceMinimal(t *testing.T) { } func TestGetInterfaceFull(t *testing.T) { + t.Parallel() + // arrange getResponsePayload := ` { @@ -1547,7 +1569,7 @@ func TestGetInterfaceFull(t *testing.T) { "snmp_id": "1", "snmp_speed": "15", "snmp_type": null, - "snmp_alias": "interace-description-1", + "snmp_alias": "interface-description-1", "interface_ip": "127.0.0.1", "interface_description": "testapi-interface-1", "interface_kvs": "", @@ -1557,7 +1579,7 @@ func TestGetInterfaceFull(t *testing.T) { "cdate": "2021-01-13T08:50:37.068Z", "edate": "2021-01-13T08:55:59.403Z", "initial_snmp_id": "150", - "initial_snmp_alias": "initial-interace-description-1", + "initial_snmp_alias": "initial-interface-description-1", "initial_interface_description": "initial-testapi-interface-1", "initial_snmp_speed": "7", "interface_ip_netmask": "255.255.255.0", @@ -1600,8 +1622,8 @@ func TestGetInterfaceFull(t *testing.T) { ] } }` - transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + transport := &connection.StubTransport{ResponseBody: getResponsePayload} + devicesAPI := resources.NewDevicesAPI(transport) // act deviceID := models.ID(42) @@ -1623,13 +1645,13 @@ func TestGetInterfaceFull(t *testing.T) { assert.Equal(models.ID(42), intf.DeviceID) assert.Equal(models.ID(1), intf.SNMPID) assert.Equal(15, intf.SNMPSpeed) - assert.Equal("interace-description-1", *intf.SNMPAlias) + assert.Equal("interface-description-1", *intf.SNMPAlias) assert.Equal("127.0.0.1", *intf.InterfaceIP) assert.Equal("testapi-interface-1", intf.InterfaceDescription) assert.Equal(time.Date(2021, 1, 13, 8, 50, 37, 68*1000000, time.UTC), intf.CreatedDate) assert.Equal(time.Date(2021, 1, 13, 8, 55, 59, 403*1000000, time.UTC), intf.UpdatedDate) assert.Equal("150", *intf.InitialSNMPID) - assert.Equal("initial-interace-description-1", *intf.InitialSNMPAlias) + assert.Equal("initial-interface-description-1", *intf.InitialSNMPAlias) assert.Equal("initial-testapi-interface-1", *intf.InitialInterfaceDescription) assert.Equal(7, *intf.InitialSNMPSpeed) assert.Equal("255.255.255.0", *intf.InterfaceIPNetmask) @@ -1654,6 +1676,8 @@ func TestGetInterfaceFull(t *testing.T) { } func TestGetAllInterfaces(t *testing.T) { + t.Parallel() + // arrange getResponsePayload := ` [ @@ -1664,7 +1688,7 @@ func TestGetAllInterfaces(t *testing.T) { "snmp_id": "1", "snmp_speed": "15", "snmp_type": null, - "snmp_alias": "interace-description-1", + "snmp_alias": "interface-description-1", "interface_ip": "127.0.0.1", "interface_description": "testapi-interface-1", "interface_kvs": "", @@ -1674,7 +1698,7 @@ func TestGetAllInterfaces(t *testing.T) { "cdate": "2021-01-13T08:50:37.068Z", "edate": "2021-01-13T08:55:59.403Z", "initial_snmp_id": "150", - "initial_snmp_alias": "initial-interace-description-1", + "initial_snmp_alias": "initial-interface-description-1", "initial_interface_description": "initial-testapi-interface-1", "initial_snmp_speed": "7", "interface_ip_netmask": "255.255.255.0", @@ -1722,7 +1746,7 @@ func TestGetAllInterfaces(t *testing.T) { "snmp_id": "1", "snmp_speed": "15", "snmp_type": null, - "snmp_alias": "interace-description-1", + "snmp_alias": "interface-description-1", "interface_ip": "127.0.0.1", "interface_description": "testapi-interface-1", "interface_kvs": "", @@ -1762,7 +1786,7 @@ func TestGetAllInterfaces(t *testing.T) { "snmp_id": "1", "snmp_speed": "15", "snmp_type": null, - "snmp_alias": "interace-description-1", + "snmp_alias": "interface-description-1", "interface_ip": "127.0.0.1", "interface_description": "testapi-interface-1", "interface_kvs": "", @@ -1788,8 +1812,8 @@ func TestGetAllInterfaces(t *testing.T) { "vrf": {} } ]` - transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + transport := &connection.StubTransport{ResponseBody: getResponsePayload} + devicesAPI := resources.NewDevicesAPI(transport) // act deviceID := models.ID(42) @@ -1812,13 +1836,13 @@ func TestGetAllInterfaces(t *testing.T) { assert.Equal(models.ID(42), intf.DeviceID) assert.Equal(models.ID(1), intf.SNMPID) assert.Equal(15, intf.SNMPSpeed) - assert.Equal("interace-description-1", *intf.SNMPAlias) + assert.Equal("interface-description-1", *intf.SNMPAlias) assert.Equal("127.0.0.1", *intf.InterfaceIP) assert.Equal("testapi-interface-1", intf.InterfaceDescription) assert.Equal(time.Date(2021, 1, 13, 8, 50, 37, 68*1000000, time.UTC), intf.CreatedDate) assert.Equal(time.Date(2021, 1, 13, 8, 55, 59, 403*1000000, time.UTC), intf.UpdatedDate) assert.Equal("150", *intf.InitialSNMPID) - assert.Equal("initial-interace-description-1", *intf.InitialSNMPAlias) + assert.Equal("initial-interface-description-1", *intf.InitialSNMPAlias) assert.Equal("initial-testapi-interface-1", *intf.InitialInterfaceDescription) assert.Equal(7, *intf.InitialSNMPSpeed) assert.Equal("255.255.255.0", *intf.InterfaceIPNetmask) @@ -1843,6 +1867,8 @@ func TestGetAllInterfaces(t *testing.T) { } func TestCreateInterfaceMinimal(t *testing.T) { + t.Parallel() + // arrange getResponsePayload := ` { @@ -1856,8 +1882,8 @@ func TestCreateInterfaceMinimal(t *testing.T) { "cdate": "2021-01-13T08:41:16.191Z", "id": "43" }` - transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + transport := &connection.StubTransport{ResponseBody: getResponsePayload} + devicesAPI := resources.NewDevicesAPI(transport) // act deviceID := models.ID(42) @@ -1898,11 +1924,13 @@ func TestCreateInterfaceMinimal(t *testing.T) { } func TestCreateInterfaceFull(t *testing.T) { + t.Parallel() + // arrange getResponsePayload := ` { "snmp_id": "243205880", - "snmp_alias": "interace-description-1", + "snmp_alias": "interface-description-1", "snmp_speed": 8, "interface_description": "testapi-interface-1", "interface_ip": "127.0.0.1", @@ -1925,8 +1953,8 @@ func TestCreateInterfaceFull(t *testing.T) { } ] }` - transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + transport := &connection.StubTransport{ResponseBody: getResponsePayload} + devicesAPI := resources.NewDevicesAPI(transport) // act vrf := models.NewVRFAttributes( @@ -1945,7 +1973,7 @@ func TestCreateInterfaceFull(t *testing.T) { 8, "testapi-interface-2", ) - models.SetOptional(&intf.SNMPAlias, "interace-description-1") + models.SetOptional(&intf.SNMPAlias, "interface-description-1") models.SetOptional(&intf.InterfaceIP, "127.0.0.1") models.SetOptional(&intf.InterfaceIPNetmask, "255.255.255.0") intf.SecondaryIPS = []models.SecondaryIP{secondaryIP1, secondaryIP2} @@ -1964,7 +1992,7 @@ func TestCreateInterfaceFull(t *testing.T) { assert.Equal(8, payload.Int("snmp_speed")) assert.Equal("testapi-interface-2", payload.String("interface_description")) - assert.Equal("interace-description-1", payload.String("snmp_alias")) + assert.Equal("interface-description-1", payload.String("snmp_alias")) assert.Equal("127.0.0.1", payload.String("interface_ip")) assert.Equal("255.255.255.0", payload.String("interface_ip_netmask")) assert.Equal("vrf-name", payload.String("vrf/name")) @@ -1990,7 +2018,7 @@ func TestCreateInterfaceFull(t *testing.T) { assert.Equal("255.255.255.240", created.SecondaryIPS[0].Netmask) assert.Equal("198.186.193.63", created.SecondaryIPS[1].Address) assert.Equal("255.255.255.225", created.SecondaryIPS[1].Netmask) - assert.Equal("interace-description-1", *created.SNMPAlias) + assert.Equal("interface-description-1", *created.SNMPAlias) assert.Equal("127.0.0.1", *created.InterfaceIP) assert.Equal("255.255.255.0", *created.InterfaceIPNetmask) assert.Equal(models.ID(39903), *created.VRFID) @@ -1998,10 +2026,12 @@ func TestCreateInterfaceFull(t *testing.T) { } func TestDeleteInterface(t *testing.T) { + t.Parallel() + // arrange deleteResponsePayload := "{}" - transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + transport := &connection.StubTransport{ResponseBody: deleteResponsePayload} + devicesAPI := resources.NewDevicesAPI(transport) // act deviceID := models.ID(42) @@ -2018,6 +2048,8 @@ func TestDeleteInterface(t *testing.T) { } func TestUpdateInterfaceMinimal(t *testing.T) { + t.Parallel() + updateResponsePayload := ` { "id": "43", @@ -2026,7 +2058,7 @@ func TestUpdateInterfaceMinimal(t *testing.T) { "snmp_id": "1", "snmp_speed": 75, "snmp_type": null, - "snmp_alias": "interace-description-1", + "snmp_alias": "interface-description-1", "interface_ip": "127.0.0.1", "interface_description": "testapi-interface-1", "interface_kvs": "", @@ -2051,8 +2083,8 @@ func TestUpdateInterfaceMinimal(t *testing.T) { "initial_interface_ip": null, "initial_interface_ip_netmask": null }` - transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + transport := &connection.StubTransport{ResponseBody: updateResponsePayload} + devicesAPI := resources.NewDevicesAPI(transport) // act deviceID := models.ID(42) @@ -2081,7 +2113,7 @@ func TestUpdateInterfaceMinimal(t *testing.T) { assert.Equal(time.Date(2021, 1, 13, 8, 50, 37, 68*1000000, time.UTC), updated.CreatedDate) assert.Equal(time.Date(2021, 1, 13, 8, 58, 27, 276*1000000, time.UTC), updated.UpdatedDate) assert.Equal(0, len(updated.SecondaryIPS)) - assert.Equal("interace-description-1", *updated.SNMPAlias) + assert.Equal("interface-description-1", *updated.SNMPAlias) assert.Equal("127.0.0.1", *updated.InterfaceIP) assert.Equal("255.255.255.0", *updated.InterfaceIPNetmask) assert.Equal(models.ID(39902), *updated.VRFID) @@ -2095,6 +2127,8 @@ func TestUpdateInterfaceMinimal(t *testing.T) { } func TestUpdateInterfaceFull(t *testing.T) { + t.Parallel() + updateResponsePayload := ` { "id": "43", @@ -2103,7 +2137,7 @@ func TestUpdateInterfaceFull(t *testing.T) { "snmp_id": "4", "snmp_speed": 44, "snmp_type": null, - "snmp_alias": "interace-description-44", + "snmp_alias": "interface-description-44", "interface_ip": "127.0.44.55", "interface_description": "testapi-interface-44", "interface_kvs": "", @@ -2128,8 +2162,8 @@ func TestUpdateInterfaceFull(t *testing.T) { "initial_interface_ip": null, "initial_interface_ip_netmask": null }` - transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + transport := &connection.StubTransport{ResponseBody: updateResponsePayload} + devicesAPI := resources.NewDevicesAPI(transport) // act vrf := models.NewVRFAttributes( @@ -2148,7 +2182,7 @@ func TestUpdateInterfaceFull(t *testing.T) { SNMPSpeed: 44, InterfaceDescription: "testapi-interface-44", } - models.SetOptional(&intf.SNMPAlias, "interace-description-44") + models.SetOptional(&intf.SNMPAlias, "interface-description-44") models.SetOptional(&intf.InterfaceIP, "127.0.44.55") models.SetOptional(&intf.InterfaceIPNetmask, "255.255.255.0") intf.VRF = vrf @@ -2164,7 +2198,7 @@ func TestUpdateInterfaceFull(t *testing.T) { payload := utils.NewJSONPayloadInspector(t, transport.RequestBody) assert.Equal("testapi-interface-44", payload.String("interface_description")) - assert.Equal("interace-description-44", payload.String("snmp_alias")) + assert.Equal("interface-description-44", payload.String("snmp_alias")) assert.Equal("127.0.44.55", payload.String("interface_ip")) assert.Equal("255.255.255.0", payload.String("interface_ip_netmask")) assert.Equal(44, payload.Int("snmp_speed")) @@ -2185,7 +2219,7 @@ func TestUpdateInterfaceFull(t *testing.T) { assert.Equal(time.Date(2021, 1, 14, 14, 43, 43, 104*1000000, time.UTC), updated.CreatedDate) assert.Equal(time.Date(2021, 1, 14, 14, 46, 21, 200*1000000, time.UTC), updated.UpdatedDate) assert.Equal(0, len(updated.SecondaryIPS)) - assert.Equal("interace-description-44", *updated.SNMPAlias) + assert.Equal("interface-description-44", *updated.SNMPAlias) assert.Equal("127.0.44.55", *updated.InterfaceIP) assert.Equal("255.255.255.0", *updated.InterfaceIPNetmask) assert.Equal(models.ID(40055), *updated.VRFID) diff --git a/kentikapi/internal/resources/my_kentik_portal.go b/kentikapi/internal/resources/my_kentik_portal.go new file mode 100644 index 00000000..68fbdd3c --- /dev/null +++ b/kentikapi/internal/resources/my_kentik_portal.go @@ -0,0 +1,62 @@ +package resources + +import ( + "context" + + "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/endpoints" + "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" + "github.com/kentik/community_sdk_golang/kentikapi/models" +) + +type MyKentikPortalAPI struct { + BaseAPI +} + +func NewMyKentikPortalAPI(transport connection.Transport) *MyKentikPortalAPI { + return &MyKentikPortalAPI{BaseAPI{Transport: transport}} +} + +// GetAll lists all tenants. +func (a *MyKentikPortalAPI) GetAll(ctx context.Context) ([]models.Tenant, error) { + var response payloads.GetAllTenantsResponse + if err := a.GetAndValidate(ctx, endpoints.TenantsPath, &response); err != nil { + return []models.Tenant{}, err + } + + return response.ToTenants() +} + +// Get Tenant Info. +func (a *MyKentikPortalAPI) Get(ctx context.Context, tenantID models.ID) (*models.Tenant, error) { + var response payloads.TenantPayload + if err := a.GetAndValidate(ctx, endpoints.GetTenantPath(tenantID), &response); err != nil { + return nil, err + } + tenant, err := response.ToTenant() + return &tenant, err +} + +func (a *MyKentikPortalAPI) CreateTenantUser(ctx context.Context, + tenantID models.ID, userEmail string) (*models.TenantUser, error) { + request := payloads.CreateTenantUserRequest{ + User: payloads.CreateTenantUserPayload{ + Email: userEmail, + }, + } + var response payloads.TenantUserPayload + if err := a.PostAndValidate(ctx, endpoints.CreateTenantUserPath(tenantID), request, &response); err != nil { + return nil, err + } + + result, err := response.ToTenantUser() + return &result, err +} + +func (a *MyKentikPortalAPI) DeleteTenantUser(ctx context.Context, tenantID models.ID, userID models.ID) error { + if err := a.DeleteAndValidate(ctx, endpoints.DeleteTenantUserPath(tenantID, userID), nil); err != nil { + return err + } + + return nil +} diff --git a/kentikapi/internal/api_resources/my_kentik_portal_test.go b/kentikapi/internal/resources/my_kentik_portal_test.go similarity index 78% rename from kentikapi/internal/api_resources/my_kentik_portal_test.go rename to kentikapi/internal/resources/my_kentik_portal_test.go index 2eab99a5..846b4f69 100644 --- a/kentikapi/internal/api_resources/my_kentik_portal_test.go +++ b/kentikapi/internal/resources/my_kentik_portal_test.go @@ -1,12 +1,12 @@ -package api_resources_test +package resources_test import ( "context" "testing" "time" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_resources" + "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/resources" "github.com/kentik/community_sdk_golang/kentikapi/internal/utils" "github.com/kentik/community_sdk_golang/kentikapi/models" "github.com/stretchr/testify/assert" @@ -14,7 +14,9 @@ import ( ) func TestTenantsList(t *testing.T) { - //arrange + t.Parallel() + + // arrange getAllResponse := ` [ { @@ -83,24 +85,25 @@ func TestTenantsList(t *testing.T) { }, } - transport := &api_connection.StubTransport{ResponseBody: getAllResponse} - myKentikPortalAPI := api_resources.NewMyKentikPortalAPI(transport) + transport := &connection.StubTransport{ResponseBody: getAllResponse} + myKentikPortalAPI := resources.NewMyKentikPortalAPI(transport) - //act + // act tenants, err := myKentikPortalAPI.GetAll(context.Background()) - //assert + // assert - //TODO(lwolanin): validate the request path passed to transport + // TODO(lwolanin): validate the request path passed to transport require.NoError(t, err) assert.Zero(t, transport.RequestBody) assert.Equal(t, expected, tenants) - } func TestGetTenantInfo(t *testing.T) { + t.Parallel() + getTenantInfoResponse := ` { "id": 577, @@ -150,22 +153,24 @@ func TestGetTenantInfo(t *testing.T) { }, } - transport := &api_connection.StubTransport{ResponseBody: getTenantInfoResponse} - myKentikPortalAPI := api_resources.NewMyKentikPortalAPI(transport) + transport := &connection.StubTransport{ResponseBody: getTenantInfoResponse} + myKentikPortalAPI := resources.NewMyKentikPortalAPI(transport) - //act + // act tenant, err := myKentikPortalAPI.Get(context.Background(), 577) // assert require.NoError(t, err) assert.Zero(t, transport.RequestBody) - //TODO(lwolanin): validate the request path passed to transport + // TODO(lwolanin): validate the request path passed to transport assert.Equal(t, &expected, tenant) } func TestTenantUserCreate(t *testing.T) { + t.Parallel() + createTenantUserResponse := ` { "id": "158564", @@ -182,15 +187,15 @@ func TestTenantUserCreate(t *testing.T) { CompanyID: 74333, } - transport := &api_connection.StubTransport{ResponseBody: createTenantUserResponse} - myKentikPortalAPI := api_resources.NewMyKentikPortalAPI(transport) + transport := &connection.StubTransport{ResponseBody: createTenantUserResponse} + myKentikPortalAPI := resources.NewMyKentikPortalAPI(transport) - //act + // act tenantUser, err := myKentikPortalAPI.CreateTenantUser(context.Background(), 577, "test@test.test") // assert - //TODO(lwolanin): Validate the request path passed to transport - //TODO(lwolanin): Verify that that there is no redundant data sent in request body + // TODO(lwolanin): Validate the request path passed to transport + // TODO(lwolanin): Verify that that there is no redundant data sent in request body require.NoError(t, err) payload := utils.NewJSONPayloadInspector(t, transport.RequestBody) @@ -201,10 +206,12 @@ func TestTenantUserCreate(t *testing.T) { } func TestTenantUserDelete(t *testing.T) { + t.Parallel() + // arrange deleteResponsePayload := "" - transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} - myKentikPortalAPI := api_resources.NewMyKentikPortalAPI(transport) + transport := &connection.StubTransport{ResponseBody: deleteResponsePayload} + myKentikPortalAPI := resources.NewMyKentikPortalAPI(transport) // act tenantID := models.ID(478) @@ -215,5 +222,5 @@ func TestTenantUserDelete(t *testing.T) { require.NoError(t, err) assert.Zero(t, transport.RequestBody) - //TODO(lwolanin): validate the request path passed to transport + // TODO(lwolanin): validate the request path passed to transport } diff --git a/kentikapi/internal/resources/plans.go b/kentikapi/internal/resources/plans.go new file mode 100644 index 00000000..47aeabb0 --- /dev/null +++ b/kentikapi/internal/resources/plans.go @@ -0,0 +1,31 @@ +package resources + +import ( + "context" + + "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/endpoints" + "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" + "github.com/kentik/community_sdk_golang/kentikapi/models" +) + +type PlansAPI struct { + BaseAPI +} + +// NewPlansAPI is constructor. +func NewPlansAPI(transport connection.Transport) *PlansAPI { + return &PlansAPI{ + BaseAPI{Transport: transport}, + } +} + +// GetAll plans. +func (a *PlansAPI) GetAll(ctx context.Context) ([]models.Plan, error) { + var response payloads.GetAllPlansResponse + if err := a.GetAndValidate(ctx, endpoints.GetAllPlans(), &response); err != nil { + return []models.Plan{}, err + } + + return response.ToPlans() +} diff --git a/kentikapi/internal/api_resources/plans_test.go b/kentikapi/internal/resources/plans_test.go similarity index 88% rename from kentikapi/internal/api_resources/plans_test.go rename to kentikapi/internal/resources/plans_test.go index 204a1bad..9f600008 100644 --- a/kentikapi/internal/api_resources/plans_test.go +++ b/kentikapi/internal/resources/plans_test.go @@ -1,17 +1,19 @@ -package api_resources_test +package resources_test import ( "context" "testing" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_resources" + "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/resources" "github.com/kentik/community_sdk_golang/kentikapi/models" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestGetAllPlans(t *testing.T) { + t.Parallel() + // arrange getResponsePayload := ` { @@ -65,8 +67,8 @@ func TestGetAllPlans(t *testing.T) { } ] }` - transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - plansAPI := api_resources.NewPlansAPI(transport) + transport := &connection.StubTransport{ResponseBody: getResponsePayload} + plansAPI := resources.NewPlansAPI(transport) // act plans, err := plansAPI.GetAll(context.Background()) diff --git a/kentikapi/internal/resources/query.go b/kentikapi/internal/resources/query.go new file mode 100644 index 00000000..4eaa56c4 --- /dev/null +++ b/kentikapi/internal/resources/query.go @@ -0,0 +1,78 @@ +package resources + +import ( + "context" + + "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/endpoints" + "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" + "github.com/kentik/community_sdk_golang/kentikapi/models" +) + +type QueryAPI struct { + BaseAPI +} + +// NewQueryAPI is constructor. +func NewQueryAPI(transport connection.Transport) *QueryAPI { + return &QueryAPI{ + BaseAPI{Transport: transport}, + } +} + +// SQL query. +func (a *QueryAPI) SQL(ctx context.Context, sql string) (models.QuerySQLResult, error) { + payload := payloads.QuerySQLRequest{Query: sql} + + var response payloads.QuerySQLResponse + if err := a.PostAndValidate(ctx, endpoints.QuerySQL(), payload, &response); err != nil { + return models.QuerySQLResult{}, err + } + + return response.ToQuerySQLResult(), nil +} + +// Data query. +func (a *QueryAPI) Data(ctx context.Context, query models.QueryObject) (models.QueryDataResult, error) { + payload, err := payloads.QueryObjectToPayload(query) + if err != nil { + return models.QueryDataResult{}, err + } + + var response payloads.QueryDataResponse + if err := a.PostAndValidate(ctx, endpoints.QueryData(), payload, &response); err != nil { + return models.QueryDataResult{}, err + } + + return response.ToQueryDataResult(), nil +} + +// Chart query. +func (a *QueryAPI) Chart(ctx context.Context, query models.QueryObject) (models.QueryChartResult, error) { + payload, err := payloads.QueryObjectToPayload(query) + if err != nil { + return models.QueryChartResult{}, err + } + + var response payloads.QueryChartResponse + if err := a.PostAndValidate(ctx, endpoints.QueryChart(), payload, &response); err != nil { + return models.QueryChartResult{}, err + } + + return response.ToQueryChartResult() +} + +// URL query. +func (a *QueryAPI) URL(ctx context.Context, query models.QueryObject) (models.QueryURLResult, error) { + payload, err := payloads.QueryObjectToPayload(query) + if err != nil { + return models.QueryURLResult{}, err + } + + var response payloads.QueryURLResponse + if err := a.PostAndValidate(ctx, endpoints.QueryURL(), payload, &response); err != nil { + return models.QueryURLResult{}, err + } + + return response.ToQueryURLResult(), nil +} diff --git a/kentikapi/internal/api_resources/query_test.go b/kentikapi/internal/resources/query_test.go similarity index 89% rename from kentikapi/internal/api_resources/query_test.go rename to kentikapi/internal/resources/query_test.go index 35406d2c..388ea306 100644 --- a/kentikapi/internal/api_resources/query_test.go +++ b/kentikapi/internal/resources/query_test.go @@ -1,4 +1,4 @@ -package api_resources_test +package resources_test import ( "context" @@ -6,8 +6,8 @@ import ( "testing" "time" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_resources" + "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/resources" "github.com/kentik/community_sdk_golang/kentikapi/internal/utils" "github.com/kentik/community_sdk_golang/kentikapi/models" "github.com/stretchr/testify/assert" @@ -15,6 +15,8 @@ import ( ) func TestQuerySQL(t *testing.T) { + t.Parallel() + // arrange querySQL := ` SELECT i_start_time, @@ -47,8 +49,8 @@ func TestQuerySQL(t *testing.T) { } ] }` - transport := &api_connection.StubTransport{ResponseBody: queryResponsePayload} - queryAPI := api_resources.NewQueryAPI(transport) + transport := &connection.StubTransport{ResponseBody: queryResponsePayload} + queryAPI := resources.NewQueryAPI(transport) // act result, err := queryAPI.SQL(context.TODO(), querySQL) @@ -84,6 +86,8 @@ func TestQuerySQL(t *testing.T) { } func TestQueryData(t *testing.T) { + t.Parallel() + // arrange queryResponsePayload := ` { @@ -123,12 +127,20 @@ func TestQueryData(t *testing.T) { } ] }` - transport := &api_connection.StubTransport{ResponseBody: queryResponsePayload} - queryAPI := api_resources.NewQueryAPI(transport) + transport := &connection.StubTransport{ResponseBody: queryResponsePayload} + queryAPI := resources.NewQueryAPI(transport) - agg1 := models.Aggregate{Name: "avg_bits_per_sec", Column: "f_sum_both_bytes", Fn: models.AggregateFunctionTypeAverage} + agg1 := models.Aggregate{ + Name: "avg_bits_per_sec", + Column: "f_sum_both_bytes", + Fn: models.AggregateFunctionTypeAverage, + } models.SetOptional(&agg1.Raw, true) - agg2 := models.Aggregate{Name: "p95th_bits_per_sec", Column: "f_sum_both_bytes", Fn: models.AggregateFunctionTypePercentile} + agg2 := models.Aggregate{ + Name: "p95th_bits_per_sec", + Column: "f_sum_both_bytes", + Fn: models.AggregateFunctionTypePercentile, + } models.SetOptional(&agg2.Rank, 95) agg3 := models.Aggregate{Name: "max_bits_per_sec", Column: "f_sum_both_bytes", Fn: models.AggregateFunctionTypeMax} query := models.NewQuery( @@ -138,8 +150,14 @@ func TestQueryData(t *testing.T) { query.Depth = 75 query.HostnameLookup = true query.Aggregates = []models.Aggregate{agg1, agg2, agg3} - models.SetOptional(&query.StartingTime, time.Date(2001, 1, 1, 7, 45, 12, 234, time.UTC)) - models.SetOptional(&query.EndingTime, time.Date(2001, 11, 23, 14, 17, 43, 458, time.UTC)) + models.SetOptional( + &query.StartingTime, + time.Date(2001, 1, 1, 7, 45, 12, 234, time.UTC), + ) + models.SetOptional( + &query.EndingTime, + time.Date(2001, 11, 23, 14, 17, 43, 458, time.UTC), + ) models.SetOptional(&query.CIDR, 32) models.SetOptional(&query.CIDR6, 128) models.SetOptional(&query.Outsort, "avg_bits_per_sec") @@ -199,17 +217,31 @@ func TestQueryData(t *testing.T) { } func TestQueryChart(t *testing.T) { + t.Parallel() + // arrange data := "ImageDataEncodedBase64==" queryResponsePayload := `{"dataUri": "data:image/png;base64,ImageDataEncodedBase64=="}` - transport := &api_connection.StubTransport{ResponseBody: queryResponsePayload} - queryAPI := api_resources.NewQueryAPI(transport) + transport := &connection.StubTransport{ResponseBody: queryResponsePayload} + queryAPI := resources.NewQueryAPI(transport) - agg1 := models.Aggregate{Name: "avg_bits_per_sec", Column: "f_sum_both_bytes", Fn: models.AggregateFunctionTypeAverage} + agg1 := models.Aggregate{ + Name: "avg_bits_per_sec", + Column: "f_sum_both_bytes", + Fn: models.AggregateFunctionTypeAverage, + } models.SetOptional(&agg1.Raw, true) - agg2 := models.Aggregate{Name: "p95th_bits_per_sec", Column: "f_sum_both_bytes", Fn: models.AggregateFunctionTypePercentile} + agg2 := models.Aggregate{ + Name: "p95th_bits_per_sec", + Column: "f_sum_both_bytes", + Fn: models.AggregateFunctionTypePercentile, + } models.SetOptional(&agg2.Rank, 95) - agg3 := models.Aggregate{Name: "max_bits_per_sec", Column: "f_sum_both_bytes", Fn: models.AggregateFunctionTypeMax} + agg3 := models.Aggregate{ + Name: "max_bits_per_sec", + Column: "f_sum_both_bytes", + Fn: models.AggregateFunctionTypeMax, + } query := models.NewQuery( models.MetricTypeBytes, @@ -217,7 +249,10 @@ func TestQueryChart(t *testing.T) { ) // filter_ = Filter(filterField="dst_as", operator="=", filterValue="") // SavedFilters is dependency here // filter_group = FilterGroups(connector="All", not_=False, filters=[filter_]) // SavedFilters is dependency here - filters := models.Filters{Connector: "", FilterGroups: nil} // filterGroups=[filter_group]) // SavedFilters is dependency here + filters := models.Filters{ + Connector: "", + FilterGroups: nil, + } // filterGroups=[filter_group]) SavedFilters is dependency here query.FiltersObj = &filters query.Aggregates = []models.Aggregate{agg1, agg2, agg3} query.LookbackSeconds = 0 @@ -230,8 +265,14 @@ func TestQueryChart(t *testing.T) { query.DeviceName = []string{"dev1", "dev2"} query.MatrixBy = []string{models.DimensionTypeSrcGeoCity.String(), models.DimensionTypeDstGeoCity.String()} query.Descriptor = "descriptor" - models.SetOptional(&query.StartingTime, time.Date(2001, 1, 1, 7, 45, 12, 234, time.UTC)) - models.SetOptional(&query.EndingTime, time.Date(2001, 11, 23, 14, 17, 43, 458, time.UTC)) + models.SetOptional( + &query.StartingTime, + time.Date(2001, 1, 1, 7, 45, 12, 234, time.UTC), + ) + models.SetOptional( + &query.EndingTime, + time.Date(2001, 11, 23, 14, 17, 43, 458, time.UTC), + ) models.SetOptional(&query.CIDR, 32) models.SetOptional(&query.CIDR6, 128) models.SetOptional(&query.Outsort, "avg_bits_per_sec") @@ -320,11 +361,13 @@ func TestQueryChart(t *testing.T) { } func TestQueryURL(t *testing.T) { + t.Parallel() + // arrange unquotedResponse := "https://portal.kentik.com/portal/#Charts/shortUrl/e0d24b3cc8dfe41f9093668e531cbe96" queryResponsePayload := `"` + unquotedResponse + `"` // actual response is url in quotation marks - transport := &api_connection.StubTransport{ResponseBody: queryResponsePayload} - queryAPI := api_resources.NewQueryAPI(transport) + transport := &connection.StubTransport{ResponseBody: queryResponsePayload} + queryAPI := resources.NewQueryAPI(transport) agg1 := models.Aggregate{Name: "avg_bits_per_sec", Column: "f_sum_both_bytes", Fn: models.AggregateFunctionTypeAverage} models.SetOptional(&agg1.Raw, true) diff --git a/kentikapi/internal/resources/saved_filters.go b/kentikapi/internal/resources/saved_filters.go new file mode 100644 index 00000000..17cad6f0 --- /dev/null +++ b/kentikapi/internal/resources/saved_filters.go @@ -0,0 +1,67 @@ +package resources + +import ( + "context" + + "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/endpoints" + "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" + "github.com/kentik/community_sdk_golang/kentikapi/models" +) + +type SavedFiltersAPI struct { + BaseAPI +} + +func NewSavedFiltersAPI(transport connection.Transport) *SavedFiltersAPI { + return &SavedFiltersAPI{BaseAPI{Transport: transport}} +} + +func (a *SavedFiltersAPI) GetAll(ctx context.Context) ([]models.SavedFilter, error) { + var response payloads.GetAllSavedFilterResponse + if err := a.GetAndValidate(ctx, endpoints.SavedFiltersPath, &response); err != nil { + return nil, err + } + + return response.ToSavedFilters() +} + +func (a *SavedFiltersAPI) Get(ctx context.Context, filterID models.ID) (*models.SavedFilter, error) { + var response payloads.GetSavedFilterResponse + err := a.GetAndValidate(ctx, endpoints.GetSavedFilter(filterID), &response) + if err != nil { + return nil, err + } + + savedFilter, err := response.ToSavedFilter() + + return &savedFilter, err +} + +func (a *SavedFiltersAPI) Create(ctx context.Context, savedFilter models.SavedFilter) (*models.SavedFilter, error) { + payload := payloads.SavedFilterToCreatePayload(savedFilter) + + var response payloads.CreateSavedFilterResponse + if err := a.PostAndValidate(ctx, endpoints.SavedFilterPath, payload, &response); err != nil { + return nil, err + } + + result, err := response.ToSavedFilter() + return &result, err +} + +func (a *SavedFiltersAPI) Update(ctx context.Context, savedFilter models.SavedFilter) (*models.SavedFilter, error) { + payload := payloads.SavedFilterToUpdatePayload(savedFilter) + + var response payloads.UpdateSavedFilterResponse + if err := a.UpdateAndValidate(ctx, endpoints.GetSavedFilter(savedFilter.ID), payload, &response); err != nil { + return nil, err + } + + result, err := response.ToSavedFilter() + return &result, err +} + +func (a *SavedFiltersAPI) Detete(ctx context.Context, id models.ID) error { + return a.DeleteAndValidate(ctx, endpoints.GetSavedFilter(id), nil) +} diff --git a/kentikapi/internal/api_resources/saved_filters_test.go b/kentikapi/internal/resources/saved_filters_test.go similarity index 84% rename from kentikapi/internal/api_resources/saved_filters_test.go rename to kentikapi/internal/resources/saved_filters_test.go index e230df96..9ef95a1f 100644 --- a/kentikapi/internal/api_resources/saved_filters_test.go +++ b/kentikapi/internal/resources/saved_filters_test.go @@ -1,17 +1,19 @@ -package api_resources_test +package resources_test import ( "context" "testing" "time" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_resources" + "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/resources" "github.com/kentik/community_sdk_golang/kentikapi/models" "github.com/stretchr/testify/assert" ) func TestSavedFiltersList(t *testing.T) { + t.Parallel() + getAllresponsePayload := ` [ { @@ -124,8 +126,8 @@ func TestSavedFiltersList(t *testing.T) { }, } - transport := &api_connection.StubTransport{ResponseBody: getAllresponsePayload} - savedFiltersAPI := api_resources.NewSavedFiltersAPI(transport) + transport := &connection.StubTransport{ResponseBody: getAllresponsePayload} + savedFiltersAPI := resources.NewSavedFiltersAPI(transport) savedFilters, err := savedFiltersAPI.GetAll(context.Background()) @@ -136,6 +138,8 @@ func TestSavedFiltersList(t *testing.T) { } func TestGetSavedFilterInfo(t *testing.T) { + t.Parallel() + getResponsePayload := ` { "id": 8275, @@ -188,8 +192,8 @@ func TestGetSavedFilterInfo(t *testing.T) { FilterLevel: "company", } - transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - savedFiltersAPI := api_resources.NewSavedFiltersAPI(transport) + transport := &connection.StubTransport{ResponseBody: getResponsePayload} + savedFiltersAPI := resources.NewSavedFiltersAPI(transport) savedFilter, err := savedFiltersAPI.Get(context.Background(), 8275) @@ -200,6 +204,8 @@ func TestGetSavedFilterInfo(t *testing.T) { } func TestCreateSavedFilter(t *testing.T) { + t.Parallel() + postResponsePayload := ` { "filter_name":"test_filter1", @@ -250,12 +256,14 @@ func TestCreateSavedFilter(t *testing.T) { ID: 8152, } // TODO(lwolanin): To test request payloads use JSONPayloadInspector like in most of tests - expectedRequestPayload := "{\"filter_name\":\"test_filter1\",\"filter_description\":\"This is test filter description\",\"cdate\":\"0001-01-01T00:00:00Z\"," + - "\"edate\":\"0001-01-01T00:00:00Z\",\"filters\":{\"connector\":\"All\",\"filterGroups\":[{\"connector\":\"All\",\"not\":false," + - "\"filters\":[{\"filterField\":\"dst_as\",\"filterValue\":\"81\",\"operator\":\"=\"}]}]}}" + expectedRequestPayload := "{\"filter_name\":\"test_filter1\"," + + "\"filter_description\":\"This is test filter description\",\"cdate\":\"0001-01-01T00:00:00Z\"," + + "\"edate\":\"0001-01-01T00:00:00Z\",\"filters\":{\"connector\":\"All\"," + + "\"filterGroups\":[{\"connector\":\"All\",\"not\":false,\"filters\":[{\"filterField\":\"dst_as\"," + + "\"filterValue\":\"81\",\"operator\":\"=\"}]}]}}" - transport := &api_connection.StubTransport{ResponseBody: postResponsePayload} - savedFiltersAPI := api_resources.NewSavedFiltersAPI(transport) + transport := &connection.StubTransport{ResponseBody: postResponsePayload} + savedFiltersAPI := resources.NewSavedFiltersAPI(transport) newSavedFilter := models.SavedFilter{ FilterName: "test_filter1", @@ -286,6 +294,8 @@ func TestCreateSavedFilter(t *testing.T) { } func TestUpdateSavedFilter(t *testing.T) { + t.Parallel() + updateResponsePayload := ` { "id":8153, @@ -309,12 +319,14 @@ func TestUpdateSavedFilter(t *testing.T) { "edate":"2020-12-16T11:26:19.187Z", "filter_level":"company" }` - expectedRequestPayload := "{\"id\":8153,\"filter_name\":\"test_filter1\",\"filter_description\":\"Updated Saved Filter description\"," + - "\"cdate\":\"0001-01-01T00:00:00Z\",\"edate\":\"0001-01-01T00:00:00Z\",\"filters\":{\"connector\":\"All\",\"filterGroups\":" + - "[{\"connector\":\"All\",\"not\":false,\"filters\":[{\"filterField\":\"dst_as\",\"filterValue\":\"81\",\"operator\":\"=\"}]}]}}" + expectedRequestPayload := "{\"id\":8153,\"filter_name\":\"test_filter1\"," + + "\"filter_description\":\"Updated Saved Filter description\",\"cdate\":\"0001-01-01T00:00:00Z\"," + + "\"edate\":\"0001-01-01T00:00:00Z\",\"filters\":{\"connector\":\"All\"," + + "\"filterGroups\":[{\"connector\":\"All\",\"not\":false,\"filters\":[{\"filterField\":\"dst_as\"," + + "\"filterValue\":\"81\",\"operator\":\"=\"}]}]}}" - transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} - savedFiltersAPI := api_resources.NewSavedFiltersAPI(transport) + transport := &connection.StubTransport{ResponseBody: updateResponsePayload} + savedFiltersAPI := resources.NewSavedFiltersAPI(transport) filterID := 8153 toUpdate := models.SavedFilter{ @@ -347,10 +359,12 @@ func TestUpdateSavedFilter(t *testing.T) { } func TestDeleteSavedFilter(t *testing.T) { + t.Parallel() + deleteResponsePayload := "" - transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} - savedFiltersAPI := api_resources.NewSavedFiltersAPI(transport) + transport := &connection.StubTransport{ResponseBody: deleteResponsePayload} + savedFiltersAPI := resources.NewSavedFiltersAPI(transport) filterID := 8153 err := savedFiltersAPI.Detete(context.Background(), filterID) diff --git a/kentikapi/internal/resources/sites.go b/kentikapi/internal/resources/sites.go new file mode 100644 index 00000000..80bce688 --- /dev/null +++ b/kentikapi/internal/resources/sites.go @@ -0,0 +1,85 @@ +package resources + +import ( + "context" + + "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/endpoints" + "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" + "github.com/kentik/community_sdk_golang/kentikapi/models" +) + +type SitesAPI struct { + BaseAPI +} + +// NewSitesAPI is constructor. +func NewSitesAPI(transport connection.Transport) *SitesAPI { + return &SitesAPI{ + BaseAPI{Transport: transport}, + } +} + +// GetAll sites. +func (a *SitesAPI) GetAll(ctx context.Context) ([]models.Site, error) { + var response payloads.GetAllSitesResponse + if err := a.GetAndValidate(ctx, endpoints.GetAllSites(), &response); err != nil { + return []models.Site{}, err + } + + return response.ToSites() +} + +// Get site with given ID. +func (a *SitesAPI) Get(ctx context.Context, id models.ID) (*models.Site, error) { + var response payloads.GetSiteResponse + if err := a.GetAndValidate(ctx, endpoints.GetSite(id), &response); err != nil { + return nil, err + } + + site, err := response.ToSite() + return &site, err +} + +// Create new site. +func (a *SitesAPI) Create(ctx context.Context, site models.Site) (*models.Site, error) { + payload, err := payloads.SiteToPayload(site) + if err != nil { + return nil, err + } + + request := payloads.CreateSiteRequest{Payload: payload} + var response payloads.CreateSiteResponse + if err = a.PostAndValidate(ctx, endpoints.CreateSite(), request, &response); err != nil { + return nil, err + } + + result, err := response.ToSite() + return &result, err +} + +// Update site. +func (a *SitesAPI) Update(ctx context.Context, site models.Site) (*models.Site, error) { + payload, err := payloads.SiteToPayload(site) + if err != nil { + return nil, err + } + + request := payloads.UpdateSiteRequest{Payload: payload} + var response payloads.UpdateSiteResponse + if err = a.UpdateAndValidate(ctx, endpoints.UpdateSite(site.ID), request, &response); err != nil { + return nil, err + } + + result, err := response.ToSite() + return &result, err +} + +// Delete site. +func (a *SitesAPI) Delete(ctx context.Context, id models.ID) error { + if err := a.DeleteAndValidate(ctx, endpoints.DeleteSite(id), nil); err != nil { + return err + } + + return nil +} diff --git a/kentikapi/internal/api_resources/sites_test.go b/kentikapi/internal/resources/sites_test.go similarity index 84% rename from kentikapi/internal/api_resources/sites_test.go rename to kentikapi/internal/resources/sites_test.go index fb52bacf..92ba55b3 100644 --- a/kentikapi/internal/api_resources/sites_test.go +++ b/kentikapi/internal/resources/sites_test.go @@ -1,11 +1,11 @@ -package api_resources_test +package resources_test import ( "context" "testing" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_resources" + "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/resources" "github.com/kentik/community_sdk_golang/kentikapi/internal/utils" "github.com/kentik/community_sdk_golang/kentikapi/models" "github.com/stretchr/testify/assert" @@ -13,6 +13,8 @@ import ( ) func TestGetSite(t *testing.T) { + t.Parallel() + // arrange getResponsePayload := ` { @@ -24,8 +26,8 @@ func TestGetSite(t *testing.T) { "company_id": 3250 } }` - transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - sitesAPI := api_resources.NewSitesAPI(transport) + transport := &connection.StubTransport{ResponseBody: getResponsePayload} + sitesAPI := resources.NewSitesAPI(transport) siteID := models.ID(42) // act @@ -47,6 +49,8 @@ func TestGetSite(t *testing.T) { } func TestGetAllSites(t *testing.T) { + t.Parallel() + // arrange getResponsePayload := ` { @@ -74,8 +78,8 @@ func TestGetAllSites(t *testing.T) { } ] }` - transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - sitesAPI := api_resources.NewSitesAPI(transport) + transport := &connection.StubTransport{ResponseBody: getResponsePayload} + sitesAPI := resources.NewSitesAPI(transport) // act sites, err := sitesAPI.GetAll(context.Background()) @@ -113,6 +117,8 @@ func TestGetAllSites(t *testing.T) { } func TestCreateSite(t *testing.T) { + t.Parallel() + // arrange createResponsePayload := ` { @@ -124,8 +130,8 @@ func TestCreateSite(t *testing.T) { "company_id": "3250" } }` - transport := &api_connection.StubTransport{ResponseBody: createResponsePayload} - sitesAPI := api_resources.NewSitesAPI(transport) + transport := &connection.StubTransport{ResponseBody: createResponsePayload} + sitesAPI := resources.NewSitesAPI(transport) // act site := models.NewSite("apitest-site-1") @@ -153,6 +159,8 @@ func TestCreateSite(t *testing.T) { } func TestUpdateSite(t *testing.T) { + t.Parallel() + // arrange updateResponsePayload := ` { @@ -164,8 +172,8 @@ func TestUpdateSite(t *testing.T) { "company_id": "3250" } }` - transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} - sitesAPI := api_resources.NewSitesAPI(transport) + transport := &connection.StubTransport{ResponseBody: updateResponsePayload} + sitesAPI := resources.NewSitesAPI(transport) // act siteID := models.ID(42) @@ -193,10 +201,12 @@ func TestUpdateSite(t *testing.T) { } func TestDeleteSite(t *testing.T) { + t.Parallel() + // arrange deleteResponsePayload := "" // deleting site responds with empty body - transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} - sitesAPI := api_resources.NewSitesAPI(transport) + transport := &connection.StubTransport{ResponseBody: deleteResponsePayload} + sitesAPI := resources.NewSitesAPI(transport) // act siteID := models.ID(42) diff --git a/kentikapi/internal/api_resources/tags.go b/kentikapi/internal/resources/tags.go similarity index 55% rename from kentikapi/internal/api_resources/tags.go rename to kentikapi/internal/resources/tags.go index a8560d5a..ba149748 100644 --- a/kentikapi/internal/api_resources/tags.go +++ b/kentikapi/internal/resources/tags.go @@ -1,11 +1,12 @@ -package api_resources +//nolint:dupl +package resources import ( "context" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_endpoints" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" + "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/endpoints" + "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" "github.com/kentik/community_sdk_golang/kentikapi/models" ) @@ -15,14 +16,14 @@ type TagsAPI struct { } // NewTagsAPI creates new TagsAPI. -func NewTagsAPI(transport api_connection.Transport) *TagsAPI { +func NewTagsAPI(transport connection.Transport) *TagsAPI { return &TagsAPI{BaseAPI{Transport: transport}} } // GetAll lists tags. func (a *TagsAPI) GetAll(ctx context.Context) ([]models.Tag, error) { - var response api_payloads.GetAllTagsResponse - if err := a.GetAndValidate(ctx, api_endpoints.TagsPath, &response); err != nil { + var response payloads.GetAllTagsResponse + if err := a.GetAndValidate(ctx, endpoints.TagsPath, &response); err != nil { return nil, err } @@ -31,8 +32,8 @@ func (a *TagsAPI) GetAll(ctx context.Context) ([]models.Tag, error) { // Get retrieves tag with given ID. func (a *TagsAPI) Get(ctx context.Context, id models.ID) (*models.Tag, error) { - var response api_payloads.GetTagResponse - if err := a.GetAndValidate(ctx, api_endpoints.GetTagPath(id), &response); err != nil { + var response payloads.GetTagResponse + if err := a.GetAndValidate(ctx, endpoints.GetTagPath(id), &response); err != nil { return nil, err } @@ -41,11 +42,11 @@ func (a *TagsAPI) Get(ctx context.Context, id models.ID) (*models.Tag, error) { // Create creates new tag. func (a *TagsAPI) Create(ctx context.Context, tag models.Tag) (*models.Tag, error) { - var response api_payloads.CreateTagResponse + var response payloads.CreateTagResponse err := a.PostAndValidate( ctx, - api_endpoints.TagPath, - api_payloads.CreateTagRequest{Tag: api_payloads.TagToPayload(tag)}, + endpoints.TagPath, + payloads.CreateTagRequest{Tag: payloads.TagToPayload(tag)}, &response, ) if err != nil { @@ -57,11 +58,11 @@ func (a *TagsAPI) Create(ctx context.Context, tag models.Tag) (*models.Tag, erro // Update updates the tag. func (a *TagsAPI) Update(ctx context.Context, tag models.Tag) (*models.Tag, error) { - var response api_payloads.UpdateTagResponse + var response payloads.UpdateTagResponse err := a.UpdateAndValidate( ctx, - api_endpoints.GetTagPath(tag.ID), - api_payloads.UpdateTagRequest{Tag: api_payloads.TagToPayload(tag)}, + endpoints.GetTagPath(tag.ID), + payloads.UpdateTagRequest{Tag: payloads.TagToPayload(tag)}, &response, ) if err != nil { @@ -73,7 +74,7 @@ func (a *TagsAPI) Update(ctx context.Context, tag models.Tag) (*models.Tag, erro // Delete removes tag with given ID. func (a *TagsAPI) Delete(ctx context.Context, id models.ID) error { - if err := a.DeleteAndValidate(ctx, api_endpoints.GetTagPath(id), nil); err != nil { + if err := a.DeleteAndValidate(ctx, endpoints.GetTagPath(id), nil); err != nil { return err } diff --git a/kentikapi/internal/api_resources/users.go b/kentikapi/internal/resources/users.go similarity index 55% rename from kentikapi/internal/api_resources/users.go rename to kentikapi/internal/resources/users.go index bab743e3..b1b48b20 100644 --- a/kentikapi/internal/api_resources/users.go +++ b/kentikapi/internal/resources/users.go @@ -1,11 +1,12 @@ -package api_resources +//nolint:dupl +package resources import ( "context" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_endpoints" - "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" + "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/endpoints" + "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" "github.com/kentik/community_sdk_golang/kentikapi/models" ) @@ -15,14 +16,14 @@ type UsersAPI struct { } // NewUsersAPI creates new UsersAPI. -func NewUsersAPI(transport api_connection.Transport) *UsersAPI { +func NewUsersAPI(transport connection.Transport) *UsersAPI { return &UsersAPI{BaseAPI{Transport: transport}} } // GetAll lists users. func (a *UsersAPI) GetAll(ctx context.Context) ([]models.User, error) { - var response api_payloads.GetAllUsersResponse - if err := a.GetAndValidate(ctx, api_endpoints.UsersPath, &response); err != nil { + var response payloads.GetAllUsersResponse + if err := a.GetAndValidate(ctx, endpoints.UsersPath, &response); err != nil { return nil, err } @@ -31,8 +32,8 @@ func (a *UsersAPI) GetAll(ctx context.Context) ([]models.User, error) { // Get retrieves user with given ID. func (a *UsersAPI) Get(ctx context.Context, id models.ID) (*models.User, error) { - var response api_payloads.GetUserResponse - if err := a.GetAndValidate(ctx, api_endpoints.GetUserPath(id), &response); err != nil { + var response payloads.GetUserResponse + if err := a.GetAndValidate(ctx, endpoints.GetUserPath(id), &response); err != nil { return nil, err } @@ -41,11 +42,11 @@ func (a *UsersAPI) Get(ctx context.Context, id models.ID) (*models.User, error) // Create creates new user. func (a *UsersAPI) Create(ctx context.Context, user models.User) (*models.User, error) { - var response api_payloads.CreateUserResponse + var response payloads.CreateUserResponse err := a.PostAndValidate( ctx, - api_endpoints.UserPath, - api_payloads.CreateUserRequest{User: api_payloads.UserToPayload(user)}, + endpoints.UserPath, + payloads.CreateUserRequest{User: payloads.UserToPayload(user)}, &response, ) if err != nil { @@ -57,11 +58,11 @@ func (a *UsersAPI) Create(ctx context.Context, user models.User) (*models.User, // Update updates the user. func (a *UsersAPI) Update(ctx context.Context, user models.User) (*models.User, error) { - var response api_payloads.UpdateUserResponse + var response payloads.UpdateUserResponse err := a.UpdateAndValidate( ctx, - api_endpoints.GetUserPath(user.ID), - api_payloads.UpdateUserRequest{User: api_payloads.UserToPayload(user)}, + endpoints.GetUserPath(user.ID), + payloads.UpdateUserRequest{User: payloads.UserToPayload(user)}, &response, ) if err != nil { @@ -73,7 +74,7 @@ func (a *UsersAPI) Update(ctx context.Context, user models.User) (*models.User, // Delete removes user with given ID. func (a *UsersAPI) Delete(ctx context.Context, id models.ID) error { - if err := a.DeleteAndValidate(ctx, api_endpoints.GetUserPath(id), nil); err != nil { + if err := a.DeleteAndValidate(ctx, endpoints.GetUserPath(id), nil); err != nil { return err } diff --git a/kentikapi/internal/testutil/http.go b/kentikapi/internal/testutil/http.go index 9bb51aa5..9e49176f 100644 --- a/kentikapi/internal/testutil/http.go +++ b/kentikapi/internal/testutil/http.go @@ -54,13 +54,13 @@ func (h *SpyHTTPHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) { type MultipleResponseSpyHTTPHandler struct { t testing.TB // Responses to return to the client - responses []HttpResponse + responses []HTTPResponse // Requests spied by the handler - Requests []HttpRequest + Requests []HTTPRequest } -func NewMultipleResponseSpyHTTPHandler(t testing.TB, responses []HttpResponse) *MultipleResponseSpyHTTPHandler { +func NewMultipleResponseSpyHTTPHandler(t testing.TB, responses []HTTPResponse) *MultipleResponseSpyHTTPHandler { return &MultipleResponseSpyHTTPHandler{ t: t, responses: responses, @@ -74,9 +74,9 @@ func (h *MultipleResponseSpyHTTPHandler) ServeHTTP(rw http.ResponseWriter, r *ht err = r.Body.Close() assert.NoError(h.t, err) - h.Requests = append(h.Requests, HttpRequest{ + h.Requests = append(h.Requests, HTTPRequest{ Method: r.Method, - Url_: r.URL, + URL: r.URL, Header: r.Header, Body: string(body), }) @@ -88,9 +88,9 @@ func (h *MultipleResponseSpyHTTPHandler) ServeHTTP(rw http.ResponseWriter, r *ht assert.NoError(h.t, err) } -func (h *MultipleResponseSpyHTTPHandler) response() HttpResponse { +func (h *MultipleResponseSpyHTTPHandler) response() HTTPResponse { if len(h.Requests) > len(h.responses) { - return HttpResponse{ + return HTTPResponse{ StatusCode: http.StatusGone, Body: fmt.Sprintf( "spyHTTPHandler: unexpected request, requests count: %v, expected: %v", @@ -102,21 +102,21 @@ func (h *MultipleResponseSpyHTTPHandler) response() HttpResponse { return h.responses[len(h.Requests)-1] } -type HttpRequest struct { +type HTTPRequest struct { Method string - Url_ *url.URL + URL *url.URL Header http.Header Body string } -type HttpResponse struct { +type HTTPResponse struct { StatusCode int Body string } -func NewErrorHTTPResponse(statusCode int) HttpResponse { - return HttpResponse{ +func NewErrorHTTPResponse(statusCode int) HTTPResponse { + return HTTPResponse{ StatusCode: statusCode, Body: fmt.Sprintf(`{"error":"%v"}`, http.StatusText(statusCode)), } -} \ No newline at end of file +} diff --git a/kentikapi/internal/utils/convert.go b/kentikapi/internal/utils/convert.go index 1c68c137..fb688aac 100644 --- a/kentikapi/internal/utils/convert.go +++ b/kentikapi/internal/utils/convert.go @@ -4,12 +4,12 @@ import ( "reflect" ) -// ConvertFunc signature like: func IntToString(source int) (string, error) +// ConvertFunc signature like: func IntToString(source int) (string, error). type ConvertFunc interface{} // ConvertList transforms input list of items into output list using convertFunc. // "input" must be array or slice -// "output" must be a pointer to slice; a new slice is allocated and returned under that pointer +// "output" must be a pointer to slice; a new slice is allocated and returned under that pointer. func ConvertList(input interface{}, convertFunc ConvertFunc, output interface{}) error { tInput := reflect.TypeOf(input) if tInput.Kind() != reflect.Array && tInput.Kind() != reflect.Slice { @@ -45,7 +45,7 @@ func ConvertList(input interface{}, convertFunc ConvertFunc, output interface{}) // ConvertOrNone transforms input into output using convertFunc, unless input is nil -> then sets output to nil. // "input" must be a pointer eg *int // "output" must be a pointer to pointer eg **int -// conversion result is stored under output, or nil is set if input is nil +// conversion result is stored under output, or nil is set if input is nil. func ConvertOrNone(input interface{}, convertFunc ConvertFunc, output interface{}) error { tInput := reflect.TypeOf(input) if tInput.Kind() != reflect.Ptr { diff --git a/kentikapi/internal/utils/convert_test.go b/kentikapi/internal/utils/convert_test.go index 0ab9fd2e..67c5eeb2 100644 --- a/kentikapi/internal/utils/convert_test.go +++ b/kentikapi/internal/utils/convert_test.go @@ -9,6 +9,8 @@ import ( ) func TestConvertOrNoneReturnsValue(t *testing.T) { + t.Parallel() + // given input := new(string) *input = "42" @@ -25,8 +27,10 @@ func TestConvertOrNoneReturnsValue(t *testing.T) { } func TestConvertOrNoneReturnsNil(t *testing.T) { + t.Parallel() + // given - var input *string = nil + var input *string var output *int // when @@ -39,6 +43,8 @@ func TestConvertOrNoneReturnsNil(t *testing.T) { } func TestConvertOrNoneReturnsError(t *testing.T) { + t.Parallel() + // given input := new(string) *input = "0xFF" @@ -53,6 +59,8 @@ func TestConvertOrNoneReturnsError(t *testing.T) { } func TestConvertListSuccess(t *testing.T) { + t.Parallel() + // given input := [...]string{"-13", "22", "742"} var output []int @@ -69,6 +77,8 @@ func TestConvertListSuccess(t *testing.T) { } func TestConvertListError(t *testing.T) { + t.Parallel() + // given input := []string{"42", "0xFF"} var output []int diff --git a/kentikapi/internal/utils/json_inspector.go b/kentikapi/internal/utils/json_inspector.go index 1a42f053..8f002df7 100644 --- a/kentikapi/internal/utils/json_inspector.go +++ b/kentikapi/internal/utils/json_inspector.go @@ -10,51 +10,51 @@ import ( "github.com/stretchr/testify/require" ) -type jsonPayloadInspector struct { +type JSONPayloadInspector struct { assert *assert.Assertions require *require.Assertions doc *jsonquery.Node } // NewJSONPayloadInspector creates json inspector object for evaluating correctness of json document -// It uses XPath for addressing JSON fields -func NewJSONPayloadInspector(t *testing.T, jsonString string) *jsonPayloadInspector { +// It uses XPath for addressing JSON fields. +func NewJSONPayloadInspector(t *testing.T, jsonString string) *JSONPayloadInspector { doc, err := jsonquery.Parse(strings.NewReader(jsonString)) if err != nil { t.Fatalf("%v\n%s\n", err, jsonString) } - return &jsonPayloadInspector{assert: assert.New(t), require: require.New(t), doc: doc} + return &JSONPayloadInspector{assert: assert.New(t), require: require.New(t), doc: doc} } -// Exists checks if field at given path exists -func (i *jsonPayloadInspector) Exists(path string) bool { +// Exists checks if field at given path exists. +func (i *JSONPayloadInspector) Exists(path string) bool { return jsonquery.Find(i.doc, path) != nil } -// Get returns whatever can be found at given path or nil if nothing is there -func (i *jsonPayloadInspector) Get(path string) *jsonquery.Node { +// Get returns whatever can be found at given path or nil if nothing is there. +func (i *JSONPayloadInspector) Get(path string) *jsonquery.Node { return jsonquery.FindOne(i.doc, path) } -// GetAll returns list of whatever can be found at given path or nil if nothing is there -func (i *jsonPayloadInspector) GetAll(path string) []*jsonquery.Node { +// GetAll returns list of whatever can be found at given path or nil if nothing is there. +func (i *JSONPayloadInspector) GetAll(path string) []*jsonquery.Node { return jsonquery.Find(i.doc, path) } -// Count returns number of array elements at given path -func (i *jsonPayloadInspector) Count(path string) int { +// Count returns number of array elements at given path. +func (i *JSONPayloadInspector) Count(path string) int { return len(jsonquery.Find(i.doc, path)) } -// String returns text found at given path -func (i *jsonPayloadInspector) String(path string) string { +// String returns text found at given path. +func (i *JSONPayloadInspector) String(path string) string { doc := i.Get(path) i.require.NotNil(doc) return doc.InnerText() } -// Int returns integer found at given path -func (i *jsonPayloadInspector) Int(path string) int { +// Int returns integer found at given path. +func (i *JSONPayloadInspector) Int(path string) int { doc := i.Get(path) i.require.NotNil(doc) result, err := strconv.Atoi(doc.InnerText()) @@ -62,8 +62,9 @@ func (i *jsonPayloadInspector) Int(path string) int { return result } -// Float returns floating point number found at given path -func (i *jsonPayloadInspector) Float(path string) float64 { +// Float returns floating point number found at given path. +//nolint:gomnd +func (i *JSONPayloadInspector) Float(path string) float64 { doc := i.Get(path) i.require.NotNil(doc) result, err := strconv.ParseFloat(doc.InnerText(), 64) @@ -71,8 +72,8 @@ func (i *jsonPayloadInspector) Float(path string) float64 { return result } -// Bool returns boolean found at given path -func (i *jsonPayloadInspector) Bool(path string) bool { +// Bool returns boolean found at given path. +func (i *JSONPayloadInspector) Bool(path string) bool { doc := i.Get(path) i.require.NotNil(doc) result, err := strconv.ParseBool(doc.InnerText()) diff --git a/kentikapi/internal/validation/validate.go b/kentikapi/internal/validation/validate.go index 1270b2f6..de2a64fd 100644 --- a/kentikapi/internal/validation/validate.go +++ b/kentikapi/internal/validation/validate.go @@ -8,24 +8,26 @@ import ( type Direction string -const DirectionRequest Direction = "request" -const DirectionResponse Direction = "response" +const ( + DirectionRequest Direction = "request" + DirectionResponse Direction = "response" +) // CheckRequestRequiredFields checks if resource's required fields are not nil. -// Eg. for method=post, it returns error if any of resource's fields marked as `request:"post"`` are set to nil +// Eg. for method=post, it returns error if any of resource's fields marked as `request:"post"`` are set to nil. func CheckRequestRequiredFields(method string, resource interface{}) error { lowercaseMethod := strings.ToLower(method) return validateWrapper(lowercaseMethod, DirectionRequest, resource) } // CheckResponseRequiredFields checks if resource's required fields are not nil. -// Eg. for method=get, it returns error if any of resource's fields marked as `response:"get"`` are set to nil +// Eg. for method=get, it returns error if any of resource's fields marked as `response:"get"`` are set to nil. func CheckResponseRequiredFields(method string, resource interface{}) error { lowercaseMethod := strings.ToLower(method) return validateWrapper(lowercaseMethod, DirectionResponse, resource) } -// validateWrapper returns error containing the list of required fields that happen to be nil +// validateWrapper returns error containing the list of required fields that happen to be nil. func validateWrapper(method string, direction Direction, resource interface{}) error { missing := validate(method, string(direction), getTypeName(resource), reflect.ValueOf(resource)) if len(missing) > 0 { @@ -38,21 +40,21 @@ func getTypeName(i interface{}) string { tResource := reflect.TypeOf(i) if tResource.Kind() == reflect.Ptr { return "*" + tResource.Elem().Name() - } else { - return tResource.Name() } + return tResource.Name() } +//nolint:exhaustive func validate(method string, direction string, path string, v reflect.Value) []string { missing := make([]string, 0) switch v.Kind() { - case reflect.Struct: for i := 0; i < v.NumField(); i++ { field := v.Field(i) fieldPath := path + "." + v.Type().Field(i).Name - if (field.Kind() == reflect.Ptr || field.Kind() == reflect.Interface || field.Kind() == reflect.Slice) && field.IsNil() { + if (field.Kind() == reflect.Ptr || field.Kind() == reflect.Interface || field.Kind() == reflect.Slice) && + field.IsNil() { requiredForMethods := v.Type().Field(i).Tag.Get(direction) if strings.Contains(requiredForMethods, method) { missing = append(missing, fieldPath) @@ -78,7 +80,6 @@ func validate(method string, direction string, path string, v reflect.Value) []s default: // primitive value has no field tags so nothing to validate - } return missing } diff --git a/kentikapi/models/custom_application.go b/kentikapi/models/custom_application.go index 554321ba..1d9e1d82 100644 --- a/kentikapi/models/custom_application.go +++ b/kentikapi/models/custom_application.go @@ -19,7 +19,7 @@ type CustomApplication struct { UpdatedDate *time.Time } -// NewCustomApplication crates a CustomApplication with all required fields set +// NewCustomApplication crates a CustomApplication with all required fields set. func NewCustomApplication(name string) *CustomApplication { return &CustomApplication{Name: name} } diff --git a/kentikapi/models/custom_dimension.go b/kentikapi/models/custom_dimension.go index 71442cf3..294c6386 100644 --- a/kentikapi/models/custom_dimension.go +++ b/kentikapi/models/custom_dimension.go @@ -13,7 +13,7 @@ type CustomDimension struct { } // NewCustomDimension creates a CustomDimension with all necessary fields set -// Note: name must begin with "c_" and be unique even among already deleted custom dimensions as names are retained for 1 year +// Note: name must begin with "c_" and be unique even among already deleted custom dimensions as names are retained for 1 year. func NewCustomDimension(name, displayName string, dimensionType CustomDimensionType) *CustomDimension { return &CustomDimension{ Name: name, diff --git a/kentikapi/models/device.go b/kentikapi/models/device.go index 0395f2a1..29713aa8 100644 --- a/kentikapi/models/device.go +++ b/kentikapi/models/device.go @@ -4,15 +4,16 @@ import "time" type Device struct { // read-write properties (can be updated in update call) - PlanID *ID - SiteID *ID - DeviceDescription *string - DeviceSampleRate int - SendingIPS []string - DeviceSNMNPIP *string - DeviceSNMPCommunity *string - MinimizeSNMP *bool - DeviceBGPType *DeviceBGPType // Note: for DeviceBGPType = DeviceBGPTypeDevice, either DeviceBGPNeighborIP or DeviceBGPNeighborIPv6 is required + PlanID *ID + SiteID *ID + DeviceDescription *string + DeviceSampleRate int + SendingIPS []string + DeviceSNMNPIP *string + DeviceSNMPCommunity *string + MinimizeSNMP *bool + DeviceBGPType *DeviceBGPType // Note: for DeviceBGPType = DeviceBGPTypeDevice, + // either DeviceBGPNeighborIP or DeviceBGPNeighborIPv6 is required DeviceBGPNeighborIP *string DeviceBGPNeighborIPv6 *string DeviceBGPNeighborASN *string @@ -49,27 +50,27 @@ type Device struct { // Optional fields that can be always set include: // - DeviceDescription // - SiteID -// - DeviceBGPFlowSpec +// - DeviceBGPFlowSpec. func NewDeviceRouter( // common required - DeviceName string, - DeviceSubType DeviceSubtype, - DeviceSampleRate int, - PlanID ID, + deviceName string, + deviceSubType DeviceSubtype, + deviceSampleRate int, + planID ID, // router required - SendingIPS []string, - MinimizeSNMP bool, + sendingIPS []string, + minimizeSNMP bool, ) *Device { bgpType := DeviceBGPTypeNone // default return &Device{ DeviceType: DeviceTypeRouter, - DeviceName: DeviceName, - DeviceSubType: DeviceSubType, - DeviceSampleRate: DeviceSampleRate, - PlanID: &PlanID, + DeviceName: deviceName, + DeviceSubType: deviceSubType, + DeviceSampleRate: deviceSampleRate, + PlanID: &planID, DeviceBGPType: &bgpType, - SendingIPS: SendingIPS, - MinimizeSNMP: &MinimizeSNMP, + SendingIPS: sendingIPS, + MinimizeSNMP: &minimizeSNMP, } } @@ -77,32 +78,32 @@ func NewDeviceRouter( // Optional fields that can be set include: // - DeviceDescription // - SiteID -// - DeviceBGPFlowSpec +// - DeviceBGPFlowSpec. func NewDeviceDNS( // common required - DeviceName string, - DeviceSubType DeviceSubtype, - DeviceSampleRate int, - PlanID ID, + deviceName string, + deviceSubType DeviceSubtype, + deviceSampleRate int, + planID ID, // dns required - CDNAttr CDNAttribute, + cdnAttr CDNAttribute, ) *Device { bgpType := DeviceBGPTypeNone // default return &Device{ DeviceType: DeviceTypeHostNProbeDNSWWW, - DeviceName: DeviceName, - DeviceSubType: DeviceSubType, - DeviceSampleRate: DeviceSampleRate, - PlanID: &PlanID, + DeviceName: deviceName, + DeviceSubType: deviceSubType, + DeviceSampleRate: deviceSampleRate, + PlanID: &planID, DeviceBGPType: &bgpType, - CDNAttr: &CDNAttr, + CDNAttr: &cdnAttr, } } // WithBGPTypeDevice is alternative to WithBGPTypeOtherDevice // Optional fields that can be set for BGPTypeDevice include: // - DeviceBGPPassword -// Note: either DeviceBGPNeighborIP or DeviceBGPNeighborIPv6 is required for DeviceBGPTypeDevice +// Note: either DeviceBGPNeighborIP or DeviceBGPNeighborIPv6 is required for DeviceBGPTypeDevice. func (d *Device) WithBGPTypeDevice(deviceBGPNeighborASN string) *Device { bgpType := DeviceBGPTypeDevice d.DeviceBGPType = &bgpType @@ -110,7 +111,7 @@ func (d *Device) WithBGPTypeDevice(deviceBGPNeighborASN string) *Device { return d } -// WithBGPTypeOtherDevice is alternative to WithBGPTypeDevice +// WithBGPTypeOtherDevice is alternative to WithBGPTypeDevice. func (d *Device) WithBGPTypeOtherDevice(useBGPDeviceID ID) *Device { bgpType := DeviceBGPTypeOtherDevice d.DeviceBGPType = &bgpType @@ -149,7 +150,7 @@ func (c *SNMPv3Conf) WithPrivacy(protocol PrivacyProtocol, pass string) *SNMPv3C return c } -// DeviceSite embedded under Device differs from regular Site in that all fields are optional +// DeviceSite embedded under Device differs from regular Site in that all fields are optional. type DeviceSite struct { ID *ID CompanyID *ID @@ -158,7 +159,7 @@ type DeviceSite struct { SiteName *string } -// DevicePlan embedded under Device differs from regular Plan in that all fields are optional +// DevicePlan embedded under Device differs from regular Plan in that all fields are optional. type DevicePlan struct { ID *ID CompanyID *ID @@ -194,7 +195,7 @@ const ( type DeviceSubtype string const ( - // for DeviceType = DeviceTypeRouter + // for DeviceType = DeviceTypeRouter. DeviceSubtypeRouter DeviceSubtype = "router" DeviceSubtypeCiscoAsa DeviceSubtype = "cisco_asa" DeviceSubtypePaloalto DeviceSubtype = "paloalto" @@ -212,7 +213,7 @@ const ( DeviceSubtypeAdvancedSflow DeviceSubtype = "advanced_sflow" DeviceSubtypeA10Cgn DeviceSubtype = "a10_cgn" - // for DeviceType = DeviceTypeHostNProbeDNSWWW + // for DeviceType = DeviceTypeHostNProbeDNSWWW. DeviceSubtypeKprobe DeviceSubtype = "kprobe" DeviceSubtypeNprobe DeviceSubtype = "nprobe" DeviceSubtypeAwsSubnet DeviceSubtype = "aws_subnet" diff --git a/kentikapi/models/device_label.go b/kentikapi/models/device_label.go index 40a983b7..1c2cafe6 100644 --- a/kentikapi/models/device_label.go +++ b/kentikapi/models/device_label.go @@ -16,7 +16,7 @@ type DeviceLabel struct { UpdatedDate time.Time } -// NewDeviceLabel creates a DeviceLabel with all necessary fields set +// NewDeviceLabel creates a DeviceLabel with all necessary fields set. func NewDeviceLabel(name string, color string) *DeviceLabel { return &DeviceLabel{ Name: name, diff --git a/kentikapi/models/enum_aggregate_function_type.go b/kentikapi/models/enum_aggregate_function_type.go index 23476a02..c9c08947 100644 --- a/kentikapi/models/enum_aggregate_function_type.go +++ b/kentikapi/models/enum_aggregate_function_type.go @@ -43,12 +43,12 @@ func AggregateFunctionTypeString(s string) (AggregateFunctionType, error) { return 0, fmt.Errorf("%s does not belong to AggregateFunctionType values", s) } -// AggregateFunctionTypeValues returns all values of the enum +// AggregateFunctionTypeValues returns all values of the enum. func AggregateFunctionTypeValues() []AggregateFunctionType { return _AggregateFunctionTypeValues } -// IsAAggregateFunctionType returns "true" if the value is listed in the enum definition. "false" otherwise +// IsAAggregateFunctionType returns "true" if the value is listed in the enum definition. "false" otherwise. func (i AggregateFunctionType) IsAAggregateFunctionType() bool { for _, v := range _AggregateFunctionTypeValues { if i == v { diff --git a/kentikapi/models/enum_chart_view_type.go b/kentikapi/models/enum_chart_view_type.go index f1c00775..3227e235 100644 --- a/kentikapi/models/enum_chart_view_type.go +++ b/kentikapi/models/enum_chart_view_type.go @@ -38,12 +38,12 @@ func ChartViewTypeString(s string) (ChartViewType, error) { return 0, fmt.Errorf("%s does not belong to ChartViewType values", s) } -// ChartViewTypeValues returns all values of the enum +// ChartViewTypeValues returns all values of the enum. func ChartViewTypeValues() []ChartViewType { return _ChartViewTypeValues } -// IsAChartViewType returns "true" if the value is listed in the enum definition. "false" otherwise +// IsAChartViewType returns "true" if the value is listed in the enum definition. "false" otherwise. func (i ChartViewType) IsAChartViewType() bool { for _, v := range _ChartViewTypeValues { if i == v { diff --git a/kentikapi/models/enum_dimension_type.go b/kentikapi/models/enum_dimension_type.go index 7a597769..700ea322 100644 --- a/kentikapi/models/enum_dimension_type.go +++ b/kentikapi/models/enum_dimension_type.go @@ -79,12 +79,12 @@ func DimensionTypeString(s string) (DimensionType, error) { return 0, fmt.Errorf("%s does not belong to DimensionType values", s) } -// DimensionTypeValues returns all values of the enum +// DimensionTypeValues returns all values of the enum. func DimensionTypeValues() []DimensionType { return _DimensionTypeValues } -// IsADimensionType returns "true" if the value is listed in the enum definition. "false" otherwise +// IsADimensionType returns "true" if the value is listed in the enum definition. "false" otherwise. func (i DimensionType) IsADimensionType() bool { for _, v := range _DimensionTypeValues { if i == v { diff --git a/kentikapi/models/enum_fast_data_type.go b/kentikapi/models/enum_fast_data_type.go index 34c70a81..078d506c 100644 --- a/kentikapi/models/enum_fast_data_type.go +++ b/kentikapi/models/enum_fast_data_type.go @@ -33,12 +33,12 @@ func FastDataTypeString(s string) (FastDataType, error) { return 0, fmt.Errorf("%s does not belong to FastDataType values", s) } -// FastDataTypeValues returns all values of the enum +// FastDataTypeValues returns all values of the enum. func FastDataTypeValues() []FastDataType { return _FastDataTypeValues } -// IsAFastDataType returns "true" if the value is listed in the enum definition. "false" otherwise +// IsAFastDataType returns "true" if the value is listed in the enum definition. "false" otherwise. func (i FastDataType) IsAFastDataType() bool { for _, v := range _FastDataTypeValues { if i == v { diff --git a/kentikapi/models/enum_image_type.go b/kentikapi/models/enum_image_type.go index ed406079..b081c0ac 100644 --- a/kentikapi/models/enum_image_type.go +++ b/kentikapi/models/enum_image_type.go @@ -35,12 +35,12 @@ func ImageTypeString(s string) (ImageType, error) { return 0, fmt.Errorf("%s does not belong to ImageType values", s) } -// ImageTypeValues returns all values of the enum +// ImageTypeValues returns all values of the enum. func ImageTypeValues() []ImageType { return _ImageTypeValues } -// IsAImageType returns "true" if the value is listed in the enum definition. "false" otherwise +// IsAImageType returns "true" if the value is listed in the enum definition. "false" otherwise. func (i ImageType) IsAImageType() bool { for _, v := range _ImageTypeValues { if i == v { diff --git a/kentikapi/models/enum_metric_type.go b/kentikapi/models/enum_metric_type.go index 3256f77e..51b37c29 100644 --- a/kentikapi/models/enum_metric_type.go +++ b/kentikapi/models/enum_metric_type.go @@ -50,12 +50,12 @@ func MetricTypeString(s string) (MetricType, error) { return 0, fmt.Errorf("%s does not belong to MetricType values", s) } -// MetricTypeValues returns all values of the enum +// MetricTypeValues returns all values of the enum. func MetricTypeValues() []MetricType { return _MetricTypeValues } -// IsAMetricType returns "true" if the value is listed in the enum definition. "false" otherwise +// IsAMetricType returns "true" if the value is listed in the enum definition. "false" otherwise. func (i MetricType) IsAMetricType() bool { for _, v := range _MetricTypeValues { if i == v { diff --git a/kentikapi/models/enum_time_format.go b/kentikapi/models/enum_time_format.go index 69caa99d..aee955fa 100644 --- a/kentikapi/models/enum_time_format.go +++ b/kentikapi/models/enum_time_format.go @@ -32,12 +32,12 @@ func TimeFormatString(s string) (TimeFormat, error) { return 0, fmt.Errorf("%s does not belong to TimeFormat values", s) } -// TimeFormatValues returns all values of the enum +// TimeFormatValues returns all values of the enum. func TimeFormatValues() []TimeFormat { return _TimeFormatValues } -// IsATimeFormat returns "true" if the value is listed in the enum definition. "false" otherwise +// IsATimeFormat returns "true" if the value is listed in the enum definition. "false" otherwise. func (i TimeFormat) IsATimeFormat() bool { for _, v := range _TimeFormatValues { if i == v { diff --git a/kentikapi/models/interface.go b/kentikapi/models/interface.go index 7f62c790..22d31245 100644 --- a/kentikapi/models/interface.go +++ b/kentikapi/models/interface.go @@ -29,7 +29,7 @@ type Interface struct { TopNextHopASNs []TopNextHopASN } -// NewInterface creates a new Interface with all necessary fields set +// NewInterface creates a new Interface with all necessary fields set. func NewInterface(deviceID ID, snmpID ID, snmpSpeed int, interfaceDescription string) *Interface { return &Interface{ DeviceID: deviceID, @@ -53,7 +53,7 @@ type VRFAttributes struct { DeviceID ID } -// NewVRFAttributes creates new VRFAttributes with all necessary fields set +// NewVRFAttributes creates new VRFAttributes with all necessary fields set. func NewVRFAttributes(name string, routeTarget string, routeDistinguisher string) *VRFAttributes { return &VRFAttributes{ Name: name, diff --git a/kentikapi/models/populator.go b/kentikapi/models/populator.go index 9eeb68b1..d7802bd9 100644 --- a/kentikapi/models/populator.go +++ b/kentikapi/models/populator.go @@ -36,7 +36,7 @@ type Populator struct { UpdatedDate time.Time } -// NewPopulator creates a Populator with all necessary fields set +// NewPopulator creates a Populator with all necessary fields set. func NewPopulator(dimensionID ID, value, deviceName string, direction PopulatorDirection) *Populator { return &Populator{ DimensionID: dimensionID, diff --git a/kentikapi/models/query_object.go b/kentikapi/models/query_object.go index 161a9cfc..22b76668 100644 --- a/kentikapi/models/query_object.go +++ b/kentikapi/models/query_object.go @@ -5,7 +5,7 @@ import ( "time" ) -// QueryObject is the root object describing QueryAPI Data/Chart/URL query +// QueryObject is the root object describing QueryAPI Data/Chart/URL query. type QueryObject struct { Queries []QueryArrayItem ImageType *ImageType // used in QueryChart @@ -57,7 +57,8 @@ type Query struct { SyncAxes *bool // only used in QueryChart, QueryURL } -// NewQuery creates a Query with all required fields set +// NewQuery creates a Query with all required fields set. +//nolint:gomnd func NewQuery(metric MetricType, dimension []DimensionType) *Query { return &Query{ Metric: metric, @@ -82,7 +83,7 @@ type Aggregate struct { Raw *bool // required for chart queries } -// NewAggregate creates an Aggregate with all required fields set +// NewAggregate creates an Aggregate with all required fields set. func NewAggregate(name string, column string, fn AggregateFunctionType) Aggregate { return Aggregate{ Name: name, @@ -230,6 +231,7 @@ type QueryChartResult struct { ImageData []byte // raw chart image binary data that can be directly dumped into a file } +//nolint:gosec,gomnd func (r QueryChartResult) SaveImageAs(filename string) error { - return ioutil.WriteFile(filename, r.ImageData, 0644) + return ioutil.WriteFile(filename, r.ImageData, 0o644) } diff --git a/kentikapi/models/setoptional.go b/kentikapi/models/setoptional.go index 4e29fe57..c6b87bb8 100644 --- a/kentikapi/models/setoptional.go +++ b/kentikapi/models/setoptional.go @@ -5,7 +5,7 @@ import "reflect" // SetOptional sets output pointer to a given value that can be a constant. This is a shortcut for eg.: // name := "device name" // device.DeviceName = &name -// output must be pointer to a pointer +// output must be pointer to a pointer. func SetOptional(output interface{}, value interface{}) { tOutput := reflect.TypeOf(output) if tOutput.Kind() != reflect.Ptr || tOutput.Elem().Kind() != reflect.Ptr { diff --git a/kentikapi/models/site.go b/kentikapi/models/site.go index c3118cd4..261501ff 100644 --- a/kentikapi/models/site.go +++ b/kentikapi/models/site.go @@ -11,7 +11,7 @@ type Site struct { // NewSite creates a new Site with all necessary fields set // Optional fields that can be set for Site include: // - Longitude -// - Latitude +// - Latitude. func NewSite(name string) *Site { return &Site{ SiteName: name, diff --git a/kentikapi/tags_integration_test.go b/kentikapi/tags_integration_test.go index d44c8a39..149b6066 100644 --- a/kentikapi/tags_integration_test.go +++ b/kentikapi/tags_integration_test.go @@ -1,3 +1,4 @@ +//nolint:dupl package kentikapi_test import ( @@ -18,6 +19,8 @@ const ( ) func TestClient_GetAllTags(t *testing.T) { + t.Parallel() + tests := []struct { name string responseCode int @@ -82,7 +85,10 @@ func TestClient_GetAllTags(t *testing.T) { }, } for _, tt := range tests { + tt := tt t.Run(tt.name, func(t *testing.T) { + t.Parallel() + // arrange h := testutil.NewSpyHTTPHandler(t, tt.responseCode, []byte(tt.responseBody)) s := httptest.NewServer(h) @@ -117,6 +123,8 @@ func TestClient_GetAllTags(t *testing.T) { } func TestClient_GetTag(t *testing.T) { + t.Parallel() + tests := []struct { name string responseCode int @@ -149,7 +157,10 @@ func TestClient_GetTag(t *testing.T) { }, } for _, tt := range tests { + tt := tt t.Run(tt.name, func(t *testing.T) { + t.Parallel() + // arrange h := testutil.NewSpyHTTPHandler(t, tt.responseCode, []byte(tt.responseBody)) s := httptest.NewServer(h) @@ -184,6 +195,8 @@ func TestClient_GetTag(t *testing.T) { } func TestClient_CreateTag(t *testing.T) { + t.Parallel() + tests := []struct { name string tag models.Tag @@ -326,7 +339,10 @@ func TestClient_CreateTag(t *testing.T) { }, } for _, tt := range tests { + tt := tt t.Run(tt.name, func(t *testing.T) { + t.Parallel() + // arrange h := testutil.NewSpyHTTPHandler(t, tt.responseCode, []byte(tt.responseBody)) s := httptest.NewServer(h) @@ -362,6 +378,8 @@ func TestClient_CreateTag(t *testing.T) { } func TestClient_UpdateTag(t *testing.T) { + t.Parallel() + tests := []struct { name string tag models.Tag @@ -492,7 +510,10 @@ func TestClient_UpdateTag(t *testing.T) { }, } for _, tt := range tests { + tt := tt t.Run(tt.name, func(t *testing.T) { + t.Parallel() + // arrange h := testutil.NewSpyHTTPHandler(t, tt.responseCode, []byte(tt.responseBody)) s := httptest.NewServer(h) @@ -529,6 +550,8 @@ func TestClient_UpdateTag(t *testing.T) { } func TestClient_DeleteTag(t *testing.T) { + t.Parallel() + tests := []struct { name string responseCode int @@ -552,7 +575,10 @@ func TestClient_DeleteTag(t *testing.T) { }, } for _, tt := range tests { + tt := tt t.Run(tt.name, func(t *testing.T) { + t.Parallel() + // arrange h := testutil.NewSpyHTTPHandler(t, tt.responseCode, []byte(tt.responseBody)) s := httptest.NewServer(h) diff --git a/kentikapi/users_integration_test.go b/kentikapi/users_integration_test.go index edc465a8..98a3394f 100644 --- a/kentikapi/users_integration_test.go +++ b/kentikapi/users_integration_test.go @@ -1,3 +1,4 @@ +//nolint:dupl package kentikapi_test import ( @@ -9,13 +10,13 @@ import ( "time" "github.com/kentik/community_sdk_golang/apiv6/kentikapi/httputil" - "github.com/kentik/community_sdk_golang/kentikapi" "github.com/kentik/community_sdk_golang/kentikapi/internal/testutil" "github.com/kentik/community_sdk_golang/kentikapi/models" "github.com/stretchr/testify/assert" ) +//nolint:gosec const ( authEmailKey = "X-CH-Auth-Email" authAPITokenKey = "X-CH-Auth-API-Token" @@ -27,6 +28,8 @@ const ( type object = map[string]interface{} func TestClient_GetAllUsers(t *testing.T) { + t.Parallel() + tests := []struct { name string responseCode int @@ -159,7 +162,10 @@ func TestClient_GetAllUsers(t *testing.T) { }, } for _, tt := range tests { + tt := tt t.Run(tt.name, func(t *testing.T) { + t.Parallel() + // arrange h := testutil.NewSpyHTTPHandler(t, tt.responseCode, []byte(tt.responseBody)) s := httptest.NewServer(h) @@ -194,36 +200,38 @@ func TestClient_GetAllUsers(t *testing.T) { } func TestClient_GetUser(t *testing.T) { + t.Parallel() + tests := []struct { name string - responses []testutil.HttpResponse + responses []testutil.HTTPResponse expectedResult *models.User expectedError bool }{ { - name: "status bad request", - responses: []testutil.HttpResponse{ - {StatusCode:http.StatusBadRequest, Body:`{"error":"Bad Request"}`}, + name: "status bad request", + responses: []testutil.HTTPResponse{ + {StatusCode: http.StatusBadRequest, Body: `{"error":"Bad Request"}`}, }, expectedError: true, }, { - name: "invalid response format", - responses: []testutil.HttpResponse{ - {StatusCode:http.StatusOK, Body:"invalid JSON"}, + name: "invalid response format", + responses: []testutil.HTTPResponse{ + {StatusCode: http.StatusOK, Body: "invalid JSON"}, }, expectedError: true, }, { - name: "empty response", - responses: []testutil.HttpResponse{ - {StatusCode:http.StatusOK, Body:"{}"}, + name: "empty response", + responses: []testutil.HTTPResponse{ + {StatusCode: http.StatusOK, Body: "{}"}, }, expectedError: true, }, { - name: "user returned", - responses: []testutil.HttpResponse{ + name: "user returned", + responses: []testutil.HTTPResponse{ { - StatusCode:http.StatusOK, - Body:`{ + StatusCode: http.StatusOK, + Body: `{ "user": { "id": "145999", "username": "testuser", @@ -259,19 +267,19 @@ func TestClient_GetUser(t *testing.T) { }, }, { name: "retry on status 502 Bad Gateway until invalid response format received", - responses: []testutil.HttpResponse{ + responses: []testutil.HTTPResponse{ testutil.NewErrorHTTPResponse(http.StatusBadGateway), testutil.NewErrorHTTPResponse(http.StatusBadGateway), - {StatusCode:http.StatusOK, Body:"invalid JSON"}, + {StatusCode: http.StatusOK, Body: "invalid JSON"}, }, expectedError: true, }, { name: "retry till success when status 429 Too Many Requests received", - responses: []testutil.HttpResponse{ + responses: []testutil.HTTPResponse{ testutil.NewErrorHTTPResponse(http.StatusTooManyRequests), { - StatusCode:http.StatusOK, - Body:`{ + StatusCode: http.StatusOK, + Body: `{ "user": { "id": "145999", "username": "testuser", @@ -308,7 +316,10 @@ func TestClient_GetUser(t *testing.T) { }, } for _, tt := range tests { + tt := tt t.Run(tt.name, func(t *testing.T) { + t.Parallel() + // arrange h := testutil.NewMultipleResponseSpyHTTPHandler(t, tt.responses) s := httptest.NewServer(h) @@ -338,7 +349,7 @@ func TestClient_GetUser(t *testing.T) { assert.Equal(t, len(tt.responses), len(h.Requests), "invalid number of requests") for _, r := range h.Requests { assert.Equal(t, http.MethodGet, r.Method) - assert.Equal(t, fmt.Sprintf("/user/%v", testUserID), r.Url_.Path) + assert.Equal(t, fmt.Sprintf("/user/%v", testUserID), r.URL.Path) assert.Equal(t, dummyAuthEmail, r.Header.Get(authEmailKey)) assert.Equal(t, dummyAuthToken, r.Header.Get(authAPITokenKey)) } @@ -349,13 +360,15 @@ func TestClient_GetUser(t *testing.T) { } func TestClient_CreateUser(t *testing.T) { + t.Parallel() + tests := []struct { name string retryMax *int user models.User // expectedRequestBody is a map for the granularity of assertion diff expectedRequestBody map[string]interface{} - responses []testutil.HttpResponse + responses []testutil.HTTPResponse expectedResult *models.User expectedError bool }{ @@ -379,10 +392,10 @@ func TestClient_CreateUser(t *testing.T) { "email_product": false, }, }, - responses: []testutil.HttpResponse{ + responses: []testutil.HTTPResponse{ { - StatusCode:http.StatusCreated, - Body:`{ + StatusCode: http.StatusCreated, + Body: `{ "user": { "id": "145999", "username": "testuser", @@ -420,31 +433,31 @@ func TestClient_CreateUser(t *testing.T) { name: "status bad request", user: models.User{}, expectedRequestBody: newEmptyUserRequestBody(), - responses: []testutil.HttpResponse{ - {StatusCode:http.StatusBadRequest, Body:`{"error":"Bad Request"}`}, + responses: []testutil.HTTPResponse{ + {StatusCode: http.StatusBadRequest, Body: `{"error":"Bad Request"}`}, }, expectedError: true, }, { name: "invalid response format", user: models.User{}, expectedRequestBody: newEmptyUserRequestBody(), - responses: []testutil.HttpResponse{ - {StatusCode:http.StatusCreated, Body:"invalid JSON"}, + responses: []testutil.HTTPResponse{ + {StatusCode: http.StatusCreated, Body: "invalid JSON"}, }, expectedError: true, }, { name: "empty response", user: models.User{}, expectedRequestBody: newEmptyUserRequestBody(), - responses: []testutil.HttpResponse{ - {StatusCode:http.StatusCreated, Body:"{}"}, + responses: []testutil.HTTPResponse{ + {StatusCode: http.StatusCreated, Body: "{}"}, }, expectedError: true, }, { name: "retry 4 times and when status 429, 500, 502, 503, 504 received and last status is 429", user: models.User{}, expectedRequestBody: newEmptyUserRequestBody(), - responses: []testutil.HttpResponse{ + responses: []testutil.HTTPResponse{ testutil.NewErrorHTTPResponse(http.StatusInternalServerError), testutil.NewErrorHTTPResponse(http.StatusBadGateway), testutil.NewErrorHTTPResponse(http.StatusServiceUnavailable), @@ -457,7 +470,7 @@ func TestClient_CreateUser(t *testing.T) { user: models.User{}, expectedRequestBody: newEmptyUserRequestBody(), retryMax: intPtr(5), - responses: []testutil.HttpResponse{ + responses: []testutil.HTTPResponse{ testutil.NewErrorHTTPResponse(http.StatusInternalServerError), testutil.NewErrorHTTPResponse(http.StatusBadGateway), testutil.NewErrorHTTPResponse(http.StatusServiceUnavailable), @@ -486,12 +499,12 @@ func TestClient_CreateUser(t *testing.T) { "email_product": false, }, }, - responses: []testutil.HttpResponse{ + responses: []testutil.HTTPResponse{ testutil.NewErrorHTTPResponse(http.StatusTooManyRequests), testutil.NewErrorHTTPResponse(http.StatusTooManyRequests), { - StatusCode:http.StatusCreated, - Body:`{ + StatusCode: http.StatusCreated, + Body: `{ "user": { "id": "145999", "username": "testuser", @@ -528,7 +541,10 @@ func TestClient_CreateUser(t *testing.T) { }, } for _, tt := range tests { + tt := tt t.Run(tt.name, func(t *testing.T) { + t.Parallel() + // arrange h := testutil.NewMultipleResponseSpyHTTPHandler(t, tt.responses) s := httptest.NewServer(h) @@ -560,18 +576,19 @@ func TestClient_CreateUser(t *testing.T) { assert.Equal(t, len(tt.responses), len(h.Requests), "invalid number of requests") for _, r := range h.Requests { assert.Equal(t, http.MethodPost, r.Method) - assert.Equal(t, "/user", r.Url_.Path) + assert.Equal(t, "/user", r.URL.Path) assert.Equal(t, dummyAuthEmail, r.Header.Get(authEmailKey)) assert.Equal(t, dummyAuthToken, r.Header.Get(authAPITokenKey)) assert.Equal(t, tt.expectedRequestBody, testutil.UnmarshalJSONToIf(t, r.Body)) } assert.Equal(t, tt.expectedResult, result) - }) } } func TestClient_UpdateUser(t *testing.T) { + t.Parallel() + tests := []struct { name string user models.User @@ -669,7 +686,10 @@ func TestClient_UpdateUser(t *testing.T) { }, } for _, tt := range tests { + tt := tt t.Run(tt.name, func(t *testing.T) { + t.Parallel() + // arrange h := testutil.NewSpyHTTPHandler(t, tt.responseCode, []byte(tt.responseBody)) s := httptest.NewServer(h) @@ -706,6 +726,8 @@ func TestClient_UpdateUser(t *testing.T) { } func TestClient_DeleteUser(t *testing.T) { + t.Parallel() + tests := []struct { name string responseCode int @@ -729,7 +751,10 @@ func TestClient_DeleteUser(t *testing.T) { }, } for _, tt := range tests { + tt := tt t.Run(tt.name, func(t *testing.T) { + t.Parallel() + // arrange h := testutil.NewSpyHTTPHandler(t, tt.responseCode, []byte(tt.responseBody)) s := httptest.NewServer(h) From 9b226c5b1b26eb6c8fd9def5a12a62327cf4f4d9 Mon Sep 17 00:00:00 2001 From: maciej palczynski Date: Thu, 9 Sep 2021 10:35:17 +0200 Subject: [PATCH 2/6] Revert package renames and suppressed linters --- .golangci.yml | 3 + .../synthetics/mesh_test/metrics_matrix.go | 2 +- apiv6/kentikapi/client.go | 2 +- .../cloudexport/go/routers.go | 5 +- .../synthetics/go/routers.go | 5 +- kentikapi/client.go | 4 +- .../rest_client.go | 2 +- .../stub_transport.go | 2 +- .../transport.go | 2 +- .../{endpoints => api_endpoints}/alerting.go | 2 +- .../custom_applications.go | 2 +- .../custom_dimensions.go | 2 +- .../device_labels.go | 2 +- .../{endpoints => api_endpoints}/devices.go | 2 +- .../my_kentik_portal.go | 2 +- .../{endpoints => api_endpoints}/plans.go | 2 +- .../{endpoints => api_endpoints}/query.go | 2 +- .../saved_filters.go | 2 +- .../{endpoints => api_endpoints}/sites.go | 2 +- .../{endpoints => api_endpoints}/tags.go | 2 +- .../{endpoints => api_endpoints}/types.go | 2 +- .../{endpoints => api_endpoints}/users.go | 2 +- .../{payloads => api_payloads}/alerting.go | 2 +- .../custom_application.go | 2 +- .../custom_dimension.go | 2 +- .../{payloads => api_payloads}/device.go | 2 +- .../device_label.go | 2 +- .../{payloads => api_payloads}/interface.go | 2 +- .../{payloads => api_payloads}/plan.go | 2 +- .../{payloads => api_payloads}/populator.go | 2 +- .../{payloads => api_payloads}/query.go | 2 +- .../{payloads => api_payloads}/query_test.go | 20 +++--- .../saved_filter.go | 2 +- .../{payloads => api_payloads}/site.go | 2 +- .../{payloads => api_payloads}/tag.go | 2 +- .../{payloads => api_payloads}/tenant.go | 2 +- .../{payloads => api_payloads}/types.go | 2 +- .../{payloads => api_payloads}/types_test.go | 24 +++---- .../{payloads => api_payloads}/user.go | 2 +- kentikapi/internal/resources/alerting.go | 22 +++---- kentikapi/internal/resources/alerting_test.go | 8 +-- kentikapi/internal/resources/base.go | 4 +- .../internal/resources/custom_applications.go | 31 ++++----- .../resources/custom_applications_test.go | 10 +-- .../internal/resources/custom_dimensions.go | 52 +++++++-------- .../resources/custom_dimensions_test.go | 18 +++--- kentikapi/internal/resources/device_labels.go | 36 +++++------ .../internal/resources/device_labels_test.go | 12 ++-- kentikapi/internal/resources/devices.go | 64 +++++++++---------- kentikapi/internal/resources/devices_test.go | 32 +++++----- .../internal/resources/my_kentik_portal.go | 26 ++++---- .../resources/my_kentik_portal_test.go | 10 +-- kentikapi/internal/resources/plans.go | 12 ++-- kentikapi/internal/resources/plans_test.go | 4 +- kentikapi/internal/resources/query.go | 32 +++++----- kentikapi/internal/resources/query_test.go | 10 +-- kentikapi/internal/resources/saved_filters.go | 30 ++++----- .../internal/resources/saved_filters_test.go | 12 ++-- kentikapi/internal/resources/sites.go | 34 +++++----- kentikapi/internal/resources/sites_test.go | 12 ++-- kentikapi/internal/resources/tags.go | 30 ++++----- kentikapi/internal/resources/users.go | 30 ++++----- 62 files changed, 332 insertions(+), 326 deletions(-) rename kentikapi/internal/{connection => api_connection}/rest_client.go (99%) rename kentikapi/internal/{connection => api_connection}/stub_transport.go (98%) rename kentikapi/internal/{connection => api_connection}/transport.go (95%) rename kentikapi/internal/{endpoints => api_endpoints}/alerting.go (98%) rename kentikapi/internal/{endpoints => api_endpoints}/custom_applications.go (94%) rename kentikapi/internal/{endpoints => api_endpoints}/custom_dimensions.go (97%) rename kentikapi/internal/{endpoints => api_endpoints}/device_labels.go (94%) rename kentikapi/internal/{endpoints => api_endpoints}/devices.go (97%) rename kentikapi/internal/{endpoints => api_endpoints}/my_kentik_portal.go (95%) rename kentikapi/internal/{endpoints => api_endpoints}/plans.go (68%) rename kentikapi/internal/{endpoints => api_endpoints}/query.go (90%) rename kentikapi/internal/{endpoints => api_endpoints}/saved_filters.go (90%) rename kentikapi/internal/{endpoints => api_endpoints}/sites.go (93%) rename kentikapi/internal/{endpoints => api_endpoints}/tags.go (87%) rename kentikapi/internal/{endpoints => api_endpoints}/types.go (81%) rename kentikapi/internal/{endpoints => api_endpoints}/users.go (87%) rename kentikapi/internal/{payloads => api_payloads}/alerting.go (99%) rename kentikapi/internal/{payloads => api_payloads}/custom_application.go (99%) rename kentikapi/internal/{payloads => api_payloads}/custom_dimension.go (99%) rename kentikapi/internal/{payloads => api_payloads}/device.go (99%) rename kentikapi/internal/{payloads => api_payloads}/device_label.go (99%) rename kentikapi/internal/{payloads => api_payloads}/interface.go (99%) rename kentikapi/internal/{payloads => api_payloads}/plan.go (99%) rename kentikapi/internal/{payloads => api_payloads}/populator.go (99%) rename kentikapi/internal/{payloads => api_payloads}/query.go (99%) rename kentikapi/internal/{payloads => api_payloads}/query_test.go (77%) rename kentikapi/internal/{payloads => api_payloads}/saved_filter.go (99%) rename kentikapi/internal/{payloads => api_payloads}/site.go (99%) rename kentikapi/internal/{payloads => api_payloads}/tag.go (99%) rename kentikapi/internal/{payloads => api_payloads}/tenant.go (99%) rename kentikapi/internal/{payloads => api_payloads}/types.go (98%) rename kentikapi/internal/{payloads => api_payloads}/types_test.go (60%) rename kentikapi/internal/{payloads => api_payloads}/user.go (99%) diff --git a/.golangci.yml b/.golangci.yml index eec43fc0..0fac662e 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -11,6 +11,9 @@ issues: max-issues-per-linter: 0 max-same-issues: 0 exclude: + # TODO: These errors should be enabled + - don't use an underscore in package name + - should not use underscores in package names # EXC0002 golint: Annoying issue about not having a comment. The rare codebase has such comments - (comment on exported (method|function|type|const)|should have( a package)? comment|comment should be of the form) - (struct (of|with)|could be) diff --git a/apiv6/examples/synthetics/mesh_test/metrics_matrix.go b/apiv6/examples/synthetics/mesh_test/metrics_matrix.go index c5af160d..c83d1686 100644 --- a/apiv6/examples/synthetics/mesh_test/metrics_matrix.go +++ b/apiv6/examples/synthetics/mesh_test/metrics_matrix.go @@ -4,7 +4,7 @@ import ( "github.com/kentik/community_sdk_golang/apiv6/kentikapi/synthetics" ) -// metricsMatrix holds "fromAgent" -> "toAgent" connection metrics +// metricsMatrix holds "fromAgent" -> "toAgent" api_connection metrics type metricsMatrix struct { agents []string cells map[string]map[string]*synthetics.V202101beta1MeshMetrics diff --git a/apiv6/kentikapi/client.go b/apiv6/kentikapi/client.go index 64ce5fa1..95e16411 100644 --- a/apiv6/kentikapi/client.go +++ b/apiv6/kentikapi/client.go @@ -34,7 +34,7 @@ type Config struct { AuthEmail string AuthToken string RetryCfg RetryConfig - // LogPayloads enables logging of request and response payloads. + // LogPayloads enables logging of request and response api_payloads. LogPayloads bool } diff --git a/apiv6/localhost_apiserver/cloudexport/go/routers.go b/apiv6/localhost_apiserver/cloudexport/go/routers.go index b14bc93b..5e34a918 100644 --- a/apiv6/localhost_apiserver/cloudexport/go/routers.go +++ b/apiv6/localhost_apiserver/cloudexport/go/routers.go @@ -12,13 +12,14 @@ package cloudexportstub import ( "encoding/json" "errors" - "github.com/gorilla/mux" "io/ioutil" "mime/multipart" "net/http" "os" "strconv" "strings" + + "github.com/gorilla/mux" ) // A Route defines the parameters for an api endpoint @@ -29,7 +30,7 @@ type Route struct { HandlerFunc http.HandlerFunc } -// Routes are a collection of defined api endpoints +// Routes are a collection of defined api api_endpoints type Routes []Route // Router defines the required methods for retrieving api routes diff --git a/apiv6/localhost_apiserver/synthetics/go/routers.go b/apiv6/localhost_apiserver/synthetics/go/routers.go index 1237fa33..0b948aee 100644 --- a/apiv6/localhost_apiserver/synthetics/go/routers.go +++ b/apiv6/localhost_apiserver/synthetics/go/routers.go @@ -12,13 +12,14 @@ package syntheticsstub import ( "encoding/json" "errors" - "github.com/gorilla/mux" "io/ioutil" "mime/multipart" "net/http" "os" "strconv" "strings" + + "github.com/gorilla/mux" ) // A Route defines the parameters for an api endpoint @@ -29,7 +30,7 @@ type Route struct { HandlerFunc http.HandlerFunc } -// Routes are a collection of defined api endpoints +// Routes are a collection of defined api api_endpoints type Routes []Route // Router defines the required methods for retrieving api routes diff --git a/kentikapi/client.go b/kentikapi/client.go index 383a0b96..3ba0edce 100644 --- a/kentikapi/client.go +++ b/kentikapi/client.go @@ -2,7 +2,7 @@ package kentikapi import ( "github.com/kentik/community_sdk_golang/apiv6/kentikapi/httputil" - "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" "github.com/kentik/community_sdk_golang/kentikapi/internal/resources" ) @@ -45,7 +45,7 @@ func NewClient(c Config) *Client { if c.APIURL == "" { c.APIURL = APIURLUS } - rc := connection.NewRestClient(connection.RestClientConfig{ + rc := api_connection.NewRestClient(api_connection.RestClientConfig{ APIURL: c.APIURL, AuthEmail: c.AuthEmail, AuthToken: c.AuthToken, diff --git a/kentikapi/internal/connection/rest_client.go b/kentikapi/internal/api_connection/rest_client.go similarity index 99% rename from kentikapi/internal/connection/rest_client.go rename to kentikapi/internal/api_connection/rest_client.go index 999050ee..5271ba4e 100644 --- a/kentikapi/internal/connection/rest_client.go +++ b/kentikapi/internal/api_connection/rest_client.go @@ -1,4 +1,4 @@ -package connection +package api_connection import ( "bytes" diff --git a/kentikapi/internal/connection/stub_transport.go b/kentikapi/internal/api_connection/stub_transport.go similarity index 98% rename from kentikapi/internal/connection/stub_transport.go rename to kentikapi/internal/api_connection/stub_transport.go index a4b87aaf..3764242b 100644 --- a/kentikapi/internal/connection/stub_transport.go +++ b/kentikapi/internal/api_connection/stub_transport.go @@ -1,4 +1,4 @@ -package connection +package api_connection import ( "context" diff --git a/kentikapi/internal/connection/transport.go b/kentikapi/internal/api_connection/transport.go similarity index 95% rename from kentikapi/internal/connection/transport.go rename to kentikapi/internal/api_connection/transport.go index fcfc90a4..936c9df4 100644 --- a/kentikapi/internal/connection/transport.go +++ b/kentikapi/internal/api_connection/transport.go @@ -1,4 +1,4 @@ -package connection +package api_connection import ( "context" diff --git a/kentikapi/internal/endpoints/alerting.go b/kentikapi/internal/api_endpoints/alerting.go similarity index 98% rename from kentikapi/internal/endpoints/alerting.go rename to kentikapi/internal/api_endpoints/alerting.go index 7e467d69..07f623d2 100644 --- a/kentikapi/internal/endpoints/alerting.go +++ b/kentikapi/internal/api_endpoints/alerting.go @@ -1,4 +1,4 @@ -package endpoints +package api_endpoints import ( "fmt" diff --git a/kentikapi/internal/endpoints/custom_applications.go b/kentikapi/internal/api_endpoints/custom_applications.go similarity index 94% rename from kentikapi/internal/endpoints/custom_applications.go rename to kentikapi/internal/api_endpoints/custom_applications.go index a1ffdeaf..2f941e30 100644 --- a/kentikapi/internal/endpoints/custom_applications.go +++ b/kentikapi/internal/api_endpoints/custom_applications.go @@ -1,4 +1,4 @@ -package endpoints +package api_endpoints import "fmt" diff --git a/kentikapi/internal/endpoints/custom_dimensions.go b/kentikapi/internal/api_endpoints/custom_dimensions.go similarity index 97% rename from kentikapi/internal/endpoints/custom_dimensions.go rename to kentikapi/internal/api_endpoints/custom_dimensions.go index afa99b88..af6ec00e 100644 --- a/kentikapi/internal/endpoints/custom_dimensions.go +++ b/kentikapi/internal/api_endpoints/custom_dimensions.go @@ -1,4 +1,4 @@ -package endpoints +package api_endpoints import "fmt" diff --git a/kentikapi/internal/endpoints/device_labels.go b/kentikapi/internal/api_endpoints/device_labels.go similarity index 94% rename from kentikapi/internal/endpoints/device_labels.go rename to kentikapi/internal/api_endpoints/device_labels.go index e57310b7..12e9217c 100644 --- a/kentikapi/internal/endpoints/device_labels.go +++ b/kentikapi/internal/api_endpoints/device_labels.go @@ -1,4 +1,4 @@ -package endpoints +package api_endpoints import ( "fmt" diff --git a/kentikapi/internal/endpoints/devices.go b/kentikapi/internal/api_endpoints/devices.go similarity index 97% rename from kentikapi/internal/endpoints/devices.go rename to kentikapi/internal/api_endpoints/devices.go index 7f0efa8c..fcdd2e6c 100644 --- a/kentikapi/internal/endpoints/devices.go +++ b/kentikapi/internal/api_endpoints/devices.go @@ -1,4 +1,4 @@ -package endpoints +package api_endpoints import ( "fmt" diff --git a/kentikapi/internal/endpoints/my_kentik_portal.go b/kentikapi/internal/api_endpoints/my_kentik_portal.go similarity index 95% rename from kentikapi/internal/endpoints/my_kentik_portal.go rename to kentikapi/internal/api_endpoints/my_kentik_portal.go index e74d5a3f..9e5f2afe 100644 --- a/kentikapi/internal/endpoints/my_kentik_portal.go +++ b/kentikapi/internal/api_endpoints/my_kentik_portal.go @@ -1,4 +1,4 @@ -package endpoints +package api_endpoints import "fmt" diff --git a/kentikapi/internal/endpoints/plans.go b/kentikapi/internal/api_endpoints/plans.go similarity index 68% rename from kentikapi/internal/endpoints/plans.go rename to kentikapi/internal/api_endpoints/plans.go index 2dfb6b0e..8967e784 100644 --- a/kentikapi/internal/endpoints/plans.go +++ b/kentikapi/internal/api_endpoints/plans.go @@ -1,4 +1,4 @@ -package endpoints +package api_endpoints func GetAllPlans() string { return "/plans" diff --git a/kentikapi/internal/endpoints/query.go b/kentikapi/internal/api_endpoints/query.go similarity index 90% rename from kentikapi/internal/endpoints/query.go rename to kentikapi/internal/api_endpoints/query.go index 636fbeac..30dac6af 100644 --- a/kentikapi/internal/endpoints/query.go +++ b/kentikapi/internal/api_endpoints/query.go @@ -1,4 +1,4 @@ -package endpoints +package api_endpoints func QuerySQL() string { return "/query/sql" diff --git a/kentikapi/internal/endpoints/saved_filters.go b/kentikapi/internal/api_endpoints/saved_filters.go similarity index 90% rename from kentikapi/internal/endpoints/saved_filters.go rename to kentikapi/internal/api_endpoints/saved_filters.go index 07c39d7f..2253c879 100644 --- a/kentikapi/internal/endpoints/saved_filters.go +++ b/kentikapi/internal/api_endpoints/saved_filters.go @@ -1,4 +1,4 @@ -package endpoints +package api_endpoints import ( "fmt" diff --git a/kentikapi/internal/endpoints/sites.go b/kentikapi/internal/api_endpoints/sites.go similarity index 93% rename from kentikapi/internal/endpoints/sites.go rename to kentikapi/internal/api_endpoints/sites.go index b8f15f3a..211820fc 100644 --- a/kentikapi/internal/endpoints/sites.go +++ b/kentikapi/internal/api_endpoints/sites.go @@ -1,4 +1,4 @@ -package endpoints +package api_endpoints import "fmt" diff --git a/kentikapi/internal/endpoints/tags.go b/kentikapi/internal/api_endpoints/tags.go similarity index 87% rename from kentikapi/internal/endpoints/tags.go rename to kentikapi/internal/api_endpoints/tags.go index b7c557c9..c9d42e49 100644 --- a/kentikapi/internal/endpoints/tags.go +++ b/kentikapi/internal/api_endpoints/tags.go @@ -1,4 +1,4 @@ -package endpoints +package api_endpoints import ( "fmt" diff --git a/kentikapi/internal/endpoints/types.go b/kentikapi/internal/api_endpoints/types.go similarity index 81% rename from kentikapi/internal/endpoints/types.go rename to kentikapi/internal/api_endpoints/types.go index ce635b47..81fad78c 100644 --- a/kentikapi/internal/endpoints/types.go +++ b/kentikapi/internal/api_endpoints/types.go @@ -1,4 +1,4 @@ -package endpoints +package api_endpoints import "github.com/kentik/community_sdk_golang/kentikapi/models" diff --git a/kentikapi/internal/endpoints/users.go b/kentikapi/internal/api_endpoints/users.go similarity index 87% rename from kentikapi/internal/endpoints/users.go rename to kentikapi/internal/api_endpoints/users.go index 984d7fac..393f5a44 100644 --- a/kentikapi/internal/endpoints/users.go +++ b/kentikapi/internal/api_endpoints/users.go @@ -1,4 +1,4 @@ -package endpoints +package api_endpoints import ( "fmt" diff --git a/kentikapi/internal/payloads/alerting.go b/kentikapi/internal/api_payloads/alerting.go similarity index 99% rename from kentikapi/internal/payloads/alerting.go rename to kentikapi/internal/api_payloads/alerting.go index e37cfd9b..0477001e 100644 --- a/kentikapi/internal/payloads/alerting.go +++ b/kentikapi/internal/api_payloads/alerting.go @@ -1,4 +1,4 @@ -package payloads +package api_payloads import ( "time" diff --git a/kentikapi/internal/payloads/custom_application.go b/kentikapi/internal/api_payloads/custom_application.go similarity index 99% rename from kentikapi/internal/payloads/custom_application.go rename to kentikapi/internal/api_payloads/custom_application.go index 25131a24..d72f7161 100644 --- a/kentikapi/internal/payloads/custom_application.go +++ b/kentikapi/internal/api_payloads/custom_application.go @@ -1,4 +1,4 @@ -package payloads +package api_payloads import ( "time" diff --git a/kentikapi/internal/payloads/custom_dimension.go b/kentikapi/internal/api_payloads/custom_dimension.go similarity index 99% rename from kentikapi/internal/payloads/custom_dimension.go rename to kentikapi/internal/api_payloads/custom_dimension.go index ee69e6f1..8fc977a6 100644 --- a/kentikapi/internal/payloads/custom_dimension.go +++ b/kentikapi/internal/api_payloads/custom_dimension.go @@ -1,4 +1,4 @@ -package payloads +package api_payloads import ( "github.com/kentik/community_sdk_golang/kentikapi/models" diff --git a/kentikapi/internal/payloads/device.go b/kentikapi/internal/api_payloads/device.go similarity index 99% rename from kentikapi/internal/payloads/device.go rename to kentikapi/internal/api_payloads/device.go index 7c4abe6b..8d1eff5b 100644 --- a/kentikapi/internal/payloads/device.go +++ b/kentikapi/internal/api_payloads/device.go @@ -1,4 +1,4 @@ -package payloads +package api_payloads import ( "time" diff --git a/kentikapi/internal/payloads/device_label.go b/kentikapi/internal/api_payloads/device_label.go similarity index 99% rename from kentikapi/internal/payloads/device_label.go rename to kentikapi/internal/api_payloads/device_label.go index 3a56a38e..59c57400 100644 --- a/kentikapi/internal/payloads/device_label.go +++ b/kentikapi/internal/api_payloads/device_label.go @@ -1,4 +1,4 @@ -package payloads +package api_payloads import ( "time" diff --git a/kentikapi/internal/payloads/interface.go b/kentikapi/internal/api_payloads/interface.go similarity index 99% rename from kentikapi/internal/payloads/interface.go rename to kentikapi/internal/api_payloads/interface.go index a10e3d73..39d40829 100644 --- a/kentikapi/internal/payloads/interface.go +++ b/kentikapi/internal/api_payloads/interface.go @@ -1,4 +1,4 @@ -package payloads +package api_payloads import ( "encoding/json" diff --git a/kentikapi/internal/payloads/plan.go b/kentikapi/internal/api_payloads/plan.go similarity index 99% rename from kentikapi/internal/payloads/plan.go rename to kentikapi/internal/api_payloads/plan.go index e93c63e6..bfc6b695 100644 --- a/kentikapi/internal/payloads/plan.go +++ b/kentikapi/internal/api_payloads/plan.go @@ -1,4 +1,4 @@ -package payloads +package api_payloads import ( "time" diff --git a/kentikapi/internal/payloads/populator.go b/kentikapi/internal/api_payloads/populator.go similarity index 99% rename from kentikapi/internal/payloads/populator.go rename to kentikapi/internal/api_payloads/populator.go index e428aa5d..92bd53df 100644 --- a/kentikapi/internal/payloads/populator.go +++ b/kentikapi/internal/api_payloads/populator.go @@ -1,4 +1,4 @@ -package payloads +package api_payloads import ( "time" diff --git a/kentikapi/internal/payloads/query.go b/kentikapi/internal/api_payloads/query.go similarity index 99% rename from kentikapi/internal/payloads/query.go rename to kentikapi/internal/api_payloads/query.go index 3fd72158..8161178b 100644 --- a/kentikapi/internal/payloads/query.go +++ b/kentikapi/internal/api_payloads/query.go @@ -1,4 +1,4 @@ -package payloads +package api_payloads import ( "encoding/base64" diff --git a/kentikapi/internal/payloads/query_test.go b/kentikapi/internal/api_payloads/query_test.go similarity index 77% rename from kentikapi/internal/payloads/query_test.go rename to kentikapi/internal/api_payloads/query_test.go index 8277387d..631daeab 100644 --- a/kentikapi/internal/payloads/query_test.go +++ b/kentikapi/internal/api_payloads/query_test.go @@ -1,11 +1,11 @@ -package payloads_test +package api_payloads_test import ( "encoding/base64" "testing" "time" - "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" "github.com/kentik/community_sdk_golang/kentikapi/models" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -17,7 +17,7 @@ func TestQueryChartResponsePNGToQueryChartResult(t *testing.T) { // arrange data := "ImagePNGEncodedBase64str" decodedData := base64Decode(t, data) - response := payloads.QueryChartResponse{DataURI: "data:image/png;base64," + data} + response := api_payloads.QueryChartResponse{DataURI: "data:image/png;base64," + data} // act result, err := response.ToQueryChartResult() @@ -34,7 +34,7 @@ func TestQueryChartResponseJPEGToQueryChartResult(t *testing.T) { // arrange data := "ImageJPGEncodedBase64str" decodedData := base64Decode(t, data) - response := payloads.QueryChartResponse{DataURI: "data:image/jpeg;base64," + data} + response := api_payloads.QueryChartResponse{DataURI: "data:image/jpeg;base64," + data} // act result, err := response.ToQueryChartResult() @@ -51,7 +51,7 @@ func TestQueryChartResponseSVGToQueryChartResult(t *testing.T) { // arrange data := "ImageSVGEncodedBase64str" decodedData := base64Decode(t, data) - response := payloads.QueryChartResponse{DataURI: "data:image/svg+xml;base64," + data} + response := api_payloads.QueryChartResponse{DataURI: "data:image/svg+xml;base64," + data} // act result, err := response.ToQueryChartResult() @@ -68,7 +68,7 @@ func TestQueryChartResponsePDFToQueryChartResult(t *testing.T) { // arrange data := "ApplicationPDFEncodedBase64str==" decodedData := base64Decode(t, data) - response := payloads.QueryChartResponse{DataURI: "data:application/pdf;base64," + data} + response := api_payloads.QueryChartResponse{DataURI: "data:application/pdf;base64," + data} // act result, err := response.ToQueryChartResult() @@ -84,7 +84,7 @@ func TestUnknownFormatResultsInError(t *testing.T) { // arrange data := "ImageBMPEncodedBase64str==" - response := payloads.QueryChartResponse{DataURI: "data:image/bmp;base64," + data} + response := api_payloads.QueryChartResponse{DataURI: "data:image/bmp;base64," + data} // act _, err := response.ToQueryChartResult() @@ -98,7 +98,7 @@ func TestUnknownEncodingResultsInError(t *testing.T) { // arrange data := "ImagePNGEncodedBase32str==" - response := payloads.QueryChartResponse{DataURI: "data:image/png;base32," + data} + response := api_payloads.QueryChartResponse{DataURI: "data:image/png;base32," + data} // act _, err := response.ToQueryChartResult() @@ -114,7 +114,7 @@ func TestFormatQueryTimeNonNil(t *testing.T) { datetime := time.Date(2001, 3, 9, 6, 45, 53, 111, time.UTC) // act - queryTime := payloads.FormatQueryTime(&datetime) + queryTime := api_payloads.FormatQueryTime(&datetime) // assert require.NotNil(t, queryTime) @@ -128,7 +128,7 @@ func TestFormatQueryTimeNil(t *testing.T) { var datetime *time.Time // act - queryTime := payloads.FormatQueryTime(datetime) + queryTime := api_payloads.FormatQueryTime(datetime) // assert assert.Nil(t, queryTime) diff --git a/kentikapi/internal/payloads/saved_filter.go b/kentikapi/internal/api_payloads/saved_filter.go similarity index 99% rename from kentikapi/internal/payloads/saved_filter.go rename to kentikapi/internal/api_payloads/saved_filter.go index 8ddc877e..0e44694d 100644 --- a/kentikapi/internal/payloads/saved_filter.go +++ b/kentikapi/internal/api_payloads/saved_filter.go @@ -1,4 +1,4 @@ -package payloads +package api_payloads import ( "time" diff --git a/kentikapi/internal/payloads/site.go b/kentikapi/internal/api_payloads/site.go similarity index 99% rename from kentikapi/internal/payloads/site.go rename to kentikapi/internal/api_payloads/site.go index 111ecb0e..0997b50b 100644 --- a/kentikapi/internal/payloads/site.go +++ b/kentikapi/internal/api_payloads/site.go @@ -1,4 +1,4 @@ -package payloads +package api_payloads import ( "github.com/kentik/community_sdk_golang/kentikapi/internal/utils" diff --git a/kentikapi/internal/payloads/tag.go b/kentikapi/internal/api_payloads/tag.go similarity index 99% rename from kentikapi/internal/payloads/tag.go rename to kentikapi/internal/api_payloads/tag.go index e9399b1f..31ea8809 100644 --- a/kentikapi/internal/payloads/tag.go +++ b/kentikapi/internal/api_payloads/tag.go @@ -1,4 +1,4 @@ -package payloads +package api_payloads import ( "time" diff --git a/kentikapi/internal/payloads/tenant.go b/kentikapi/internal/api_payloads/tenant.go similarity index 99% rename from kentikapi/internal/payloads/tenant.go rename to kentikapi/internal/api_payloads/tenant.go index a43734fc..187b9e06 100644 --- a/kentikapi/internal/payloads/tenant.go +++ b/kentikapi/internal/api_payloads/tenant.go @@ -1,4 +1,4 @@ -package payloads +package api_payloads import ( "time" diff --git a/kentikapi/internal/payloads/types.go b/kentikapi/internal/api_payloads/types.go similarity index 98% rename from kentikapi/internal/payloads/types.go rename to kentikapi/internal/api_payloads/types.go index aad06f68..a1e20093 100644 --- a/kentikapi/internal/payloads/types.go +++ b/kentikapi/internal/api_payloads/types.go @@ -1,4 +1,4 @@ -package payloads +package api_payloads import ( "encoding/json" diff --git a/kentikapi/internal/payloads/types_test.go b/kentikapi/internal/api_payloads/types_test.go similarity index 60% rename from kentikapi/internal/payloads/types_test.go rename to kentikapi/internal/api_payloads/types_test.go index 15a9f6f7..6e4dc403 100644 --- a/kentikapi/internal/payloads/types_test.go +++ b/kentikapi/internal/api_payloads/types_test.go @@ -1,10 +1,10 @@ -package payloads_test +package api_payloads_test import ( "encoding/json" "testing" - "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" "github.com/stretchr/testify/assert" ) @@ -13,36 +13,36 @@ func TestBoolAsString_UnmarshalJSON(t *testing.T) { tests := []struct { input string - expectedResult payloads.BoolAsStringOrInt + expectedResult api_payloads.BoolAsStringOrInt expectedError bool }{ { input: `true`, - expectedResult: payloads.BoolAsStringOrInt(true), + expectedResult: api_payloads.BoolAsStringOrInt(true), }, { input: `false`, - expectedResult: payloads.BoolAsStringOrInt(false), + expectedResult: api_payloads.BoolAsStringOrInt(false), }, { input: `"true"`, - expectedResult: payloads.BoolAsStringOrInt(true), + expectedResult: api_payloads.BoolAsStringOrInt(true), }, { input: `"True"`, - expectedResult: payloads.BoolAsStringOrInt(true), + expectedResult: api_payloads.BoolAsStringOrInt(true), }, { input: `"false"`, - expectedResult: payloads.BoolAsStringOrInt(false), + expectedResult: api_payloads.BoolAsStringOrInt(false), }, { input: `"False"`, - expectedResult: payloads.BoolAsStringOrInt(false), + expectedResult: api_payloads.BoolAsStringOrInt(false), }, { input: `"invalid-string"`, expectedError: true, }, { input: `1`, - expectedResult: payloads.BoolAsStringOrInt(true), + expectedResult: api_payloads.BoolAsStringOrInt(true), }, { input: `0`, - expectedResult: payloads.BoolAsStringOrInt(false), + expectedResult: api_payloads.BoolAsStringOrInt(false), }, { input: `1.0`, expectedError: true, @@ -56,7 +56,7 @@ func TestBoolAsString_UnmarshalJSON(t *testing.T) { t.Run(tt.input, func(t *testing.T) { t.Parallel() - var result payloads.BoolAsStringOrInt + var result api_payloads.BoolAsStringOrInt err := json.Unmarshal([]byte(tt.input), &result) if tt.expectedError { diff --git a/kentikapi/internal/payloads/user.go b/kentikapi/internal/api_payloads/user.go similarity index 99% rename from kentikapi/internal/payloads/user.go rename to kentikapi/internal/api_payloads/user.go index c2a5c233..d1998ae3 100644 --- a/kentikapi/internal/payloads/user.go +++ b/kentikapi/internal/api_payloads/user.go @@ -1,4 +1,4 @@ -package payloads +package api_payloads import ( "time" diff --git a/kentikapi/internal/resources/alerting.go b/kentikapi/internal/resources/alerting.go index bbd736f8..b002cfa2 100644 --- a/kentikapi/internal/resources/alerting.go +++ b/kentikapi/internal/resources/alerting.go @@ -4,9 +4,9 @@ import ( "context" "errors" - "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/endpoints" - "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_endpoints" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" "github.com/kentik/community_sdk_golang/kentikapi/models" ) @@ -15,17 +15,17 @@ type AlertingAPI struct { } // NewAlertingAPI is constructor. -func NewAlertingAPI(transport connection.Transport) *AlertingAPI { +func NewAlertingAPI(transport api_connection.Transport) *AlertingAPI { return &AlertingAPI{ BaseAPI{Transport: transport}, } } func (a *AlertingAPI) CreateManualMitigation(ctx context.Context, mm models.ManualMitigation) error { - payload := payloads.ManualMitigationToPayload(mm) - var response payloads.CreateManualMitigationResponse + payload := api_payloads.ManualMitigationToPayload(mm) + var response api_payloads.CreateManualMitigationResponse - if err := a.PostAndValidate(ctx, endpoints.ManualMitigationPath, payload, &response); err != nil { + if err := a.PostAndValidate(ctx, api_endpoints.ManualMitigationPath, payload, &response); err != nil { return err } @@ -37,9 +37,9 @@ func (a *AlertingAPI) CreateManualMitigation(ctx context.Context, mm models.Manu } func (a *AlertingAPI) GetActiveAlerts(ctx context.Context, params models.AlertsQueryParams) ([]models.Alarm, error) { - var response payloads.GetActiveAlertsResponse + var response api_payloads.GetActiveAlertsResponse - path := endpoints.GetActiveAlertsPath(params.StartTime, params.EndTime, params.FilterBy, params.FilterVal, + path := api_endpoints.GetActiveAlertsPath(params.StartTime, params.EndTime, params.FilterBy, params.FilterVal, params.ShowMitigations, params.ShowAlarms, params.ShowMatches, params.LearningMode) if err := a.GetAndValidate(ctx, path, &response); err != nil { @@ -51,8 +51,8 @@ func (a *AlertingAPI) GetActiveAlerts(ctx context.Context, params models.AlertsQ func (a *AlertingAPI) GetAlertsHistory(ctx context.Context, params models.AlertsQueryParams) ([]models.HistoricalAlert, error) { - var response payloads.GetHistoricalAlertsResponse - path := endpoints.GetAlertsHistoryPath(params.StartTime, params.EndTime, params.FilterBy, params.FilterVal, + var response api_payloads.GetHistoricalAlertsResponse + path := api_endpoints.GetAlertsHistoryPath(params.StartTime, params.EndTime, params.FilterBy, params.FilterVal, params.SortOrder, params.ShowMitigations, params.ShowAlarms, params.ShowMatches, params.LearningMode) if err := a.GetAndValidate(ctx, path, &response); err != nil { diff --git a/kentikapi/internal/resources/alerting_test.go b/kentikapi/internal/resources/alerting_test.go index a8e59701..e9993d66 100644 --- a/kentikapi/internal/resources/alerting_test.go +++ b/kentikapi/internal/resources/alerting_test.go @@ -5,7 +5,7 @@ import ( "testing" "time" - "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" "github.com/kentik/community_sdk_golang/kentikapi/internal/resources" "github.com/kentik/community_sdk_golang/kentikapi/models" "github.com/stretchr/testify/assert" @@ -28,7 +28,7 @@ func TestCrerateManualMitigation(t *testing.T) { }` expectedRequestBody := `{"ipCidr":"192.168.0.0/24","platformID":1234,"methodID":12345,"minutesBeforeAutoStop":"20"}` - transport := &connection.StubTransport{ResponseBody: createResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: createResponsePayload} alertingAPI := resources.NewAlertingAPI(transport) mm := models.ManualMitigation{ IPCidr: "192.168.0.0/24", @@ -83,7 +83,7 @@ func TestGetActiveAlerts(t *testing.T) { "alert_key_lookup": "443" } ]` - transport := &connection.StubTransport{ResponseBody: getResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} alertingAPI := resources.NewAlertingAPI(transport) alarmEndStr := "0000-00-00 00:00:00" @@ -180,7 +180,7 @@ func TestGetAlertsHistory(t *testing.T) { "alert_key_lookup": "443" } ]` - transport := &connection.StubTransport{ResponseBody: getResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} alertingAPI := resources.NewAlertingAPI(transport) dateStr := "2021-01-19 13:50:00" diff --git a/kentikapi/internal/resources/base.go b/kentikapi/internal/resources/base.go index 2dd4ada9..47b7553e 100644 --- a/kentikapi/internal/resources/base.go +++ b/kentikapi/internal/resources/base.go @@ -5,13 +5,13 @@ import ( "encoding/json" "fmt" - "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" "github.com/kentik/community_sdk_golang/kentikapi/internal/validation" ) // BaseAPI provides marshall/unmarshall + validation functionality for all resource APIs. type BaseAPI struct { - Transport connection.Transport + Transport api_connection.Transport } // GetAndValidate retrieves json at "url", unmarshalls and validates against required fields defined in struct tags of "output" diff --git a/kentikapi/internal/resources/custom_applications.go b/kentikapi/internal/resources/custom_applications.go index 559caf7a..8038e21b 100644 --- a/kentikapi/internal/resources/custom_applications.go +++ b/kentikapi/internal/resources/custom_applications.go @@ -3,9 +3,9 @@ package resources import ( "context" - "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/endpoints" - "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_endpoints" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" "github.com/kentik/community_sdk_golang/kentikapi/models" ) @@ -14,7 +14,7 @@ type CustomApplicationsAPI struct { } // NewCustomApplicationsAPI is constructor. -func NewCustomApplicationsAPI(transport connection.Transport) *CustomApplicationsAPI { +func NewCustomApplicationsAPI(transport api_connection.Transport) *CustomApplicationsAPI { return &CustomApplicationsAPI{ BaseAPI{Transport: transport}, } @@ -22,8 +22,8 @@ func NewCustomApplicationsAPI(transport connection.Transport) *CustomApplication // GetAll custom applications. func (a *CustomApplicationsAPI) GetAll(ctx context.Context) ([]models.CustomApplication, error) { - var response payloads.GetAllCustomApplicationsResponse - if err := a.GetAndValidate(ctx, endpoints.GetAllCustomApplications(), &response); err != nil { + var response api_payloads.GetAllCustomApplicationsResponse + if err := a.GetAndValidate(ctx, api_endpoints.GetAllCustomApplications(), &response); err != nil { return []models.CustomApplication{}, err } @@ -33,10 +33,10 @@ func (a *CustomApplicationsAPI) GetAll(ctx context.Context) ([]models.CustomAppl // Create new custom application. func (a *CustomApplicationsAPI) Create(ctx context.Context, customApplication models.CustomApplication) (*models.CustomApplication, error) { - payload := payloads.CustomApplicationToPayload(customApplication) - request := payloads.CreateCustomApplicationRequest(payload) - var response payloads.CreateCustomApplicationResponse - if err := a.PostAndValidate(ctx, endpoints.CreateCustomApplication(), request, &response); err != nil { + payload := api_payloads.CustomApplicationToPayload(customApplication) + request := api_payloads.CreateCustomApplicationRequest(payload) + var response api_payloads.CreateCustomApplicationResponse + if err := a.PostAndValidate(ctx, api_endpoints.CreateCustomApplication(), request, &response); err != nil { return nil, err } @@ -45,12 +45,13 @@ func (a *CustomApplicationsAPI) Create(ctx context.Context, } // Update custom application. +//nolint:lll func (a *CustomApplicationsAPI) Update(ctx context.Context, customApplication models.CustomApplication) (*models.CustomApplication, error) { - payload := payloads.CustomApplicationToPayload(customApplication) - request := payloads.UpdateCustomApplicationRequest(payload) - var response payloads.UpdateCustomApplicationResponse - if err := a.UpdateAndValidate(ctx, endpoints.UpdateCustomApplication(customApplication.ID), request, &response); err != nil { + payload := api_payloads.CustomApplicationToPayload(customApplication) + request := api_payloads.UpdateCustomApplicationRequest(payload) + var response api_payloads.UpdateCustomApplicationResponse + if err := a.UpdateAndValidate(ctx, api_endpoints.UpdateCustomApplication(customApplication.ID), request, &response); err != nil { return nil, err } @@ -60,5 +61,5 @@ func (a *CustomApplicationsAPI) Update(ctx context.Context, // Delete custom application. func (a *CustomApplicationsAPI) Delete(ctx context.Context, id models.ID) error { - return a.DeleteAndValidate(ctx, endpoints.DeleteCustomApplication(id), nil) + return a.DeleteAndValidate(ctx, api_endpoints.DeleteCustomApplication(id), nil) } diff --git a/kentikapi/internal/resources/custom_applications_test.go b/kentikapi/internal/resources/custom_applications_test.go index 1457aee6..0bc2a3fc 100644 --- a/kentikapi/internal/resources/custom_applications_test.go +++ b/kentikapi/internal/resources/custom_applications_test.go @@ -6,7 +6,7 @@ import ( "testing" "time" - "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" "github.com/kentik/community_sdk_golang/kentikapi/internal/resources" "github.com/kentik/community_sdk_golang/kentikapi/internal/utils" "github.com/kentik/community_sdk_golang/kentikapi/models" @@ -46,7 +46,7 @@ func TestGetAll(t *testing.T) { "edate": "2020-12-11T07:08:20.968Z" } ]` - transport := &connection.StubTransport{ResponseBody: getResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} applicationsAPI := resources.NewCustomApplicationsAPI(transport) // act @@ -92,7 +92,7 @@ func TestCreateCustomApplication(t *testing.T) { "user_id": "144319", "company_id": "74333" }` - transport := &connection.StubTransport{ResponseBody: createResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: createResponsePayload} applicationsAPI := resources.NewCustomApplicationsAPI(transport) app := models.NewCustomApplication("apitest-customapp-1") @@ -150,7 +150,7 @@ func TestUpdateCustomApplication(t *testing.T) { "cdate": "2020-12-11T07:07:20.968Z", "edate": "2020-12-11T07:07:20.968Z" }` - transport := &connection.StubTransport{ResponseBody: updateResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} applicationsAPI := resources.NewCustomApplicationsAPI(transport) appID := models.ID(207) @@ -198,7 +198,7 @@ func TestDeleteCustomApplication(t *testing.T) { // arrange deleteResponsePayload := "" // deleting custom application responds with empty body - transport := &connection.StubTransport{ResponseBody: deleteResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} appliationsAPI := resources.NewCustomApplicationsAPI(transport) // act diff --git a/kentikapi/internal/resources/custom_dimensions.go b/kentikapi/internal/resources/custom_dimensions.go index 5c1684e8..c8b84f4b 100644 --- a/kentikapi/internal/resources/custom_dimensions.go +++ b/kentikapi/internal/resources/custom_dimensions.go @@ -3,9 +3,9 @@ package resources import ( "context" - "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/endpoints" - "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_endpoints" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" "github.com/kentik/community_sdk_golang/kentikapi/models" ) @@ -15,7 +15,7 @@ type CustomDimensionsAPI struct { } // NewCustomDimensionsAPI is constructor. -func NewCustomDimensionsAPI(transport connection.Transport) *CustomDimensionsAPI { +func NewCustomDimensionsAPI(transport api_connection.Transport) *CustomDimensionsAPI { return &CustomDimensionsAPI{ BaseAPI{Transport: transport}, &populatorsAPI{BaseAPI{Transport: transport}}, @@ -24,8 +24,8 @@ func NewCustomDimensionsAPI(transport connection.Transport) *CustomDimensionsAPI // GetAll custom dimensions. func (a *CustomDimensionsAPI) GetAll(ctx context.Context) ([]models.CustomDimension, error) { - var response payloads.GetAllCustomDimensionsResponse - if err := a.GetAndValidate(ctx, endpoints.GetAllCustomDimensions(), &response); err != nil { + var response api_payloads.GetAllCustomDimensionsResponse + if err := a.GetAndValidate(ctx, api_endpoints.GetAllCustomDimensions(), &response); err != nil { return []models.CustomDimension{}, err } @@ -34,8 +34,8 @@ func (a *CustomDimensionsAPI) GetAll(ctx context.Context) ([]models.CustomDimens // Get custom dimension with given ID. func (a *CustomDimensionsAPI) Get(ctx context.Context, id models.ID) (*models.CustomDimension, error) { - var response payloads.GetCustomDimensionResponse - if err := a.GetAndValidate(ctx, endpoints.GetCustomDimension(id), &response); err != nil { + var response api_payloads.GetCustomDimensionResponse + if err := a.GetAndValidate(ctx, api_endpoints.GetCustomDimension(id), &response); err != nil { return nil, err } @@ -46,11 +46,11 @@ func (a *CustomDimensionsAPI) Get(ctx context.Context, id models.ID) (*models.Cu // Create new custom dimension. func (a *CustomDimensionsAPI) Create(ctx context.Context, customDimension models.CustomDimension) (*models.CustomDimension, error) { - payload := payloads.CustomDimensionToPayload(customDimension) + payload := api_payloads.CustomDimensionToPayload(customDimension) - request := payloads.CreateCustomDimensionRequest(payload) - var response payloads.CreateCustomDimensionResponse - if err := a.PostAndValidate(ctx, endpoints.CreateCustomDimension(), request, &response); err != nil { + request := api_payloads.CreateCustomDimensionRequest(payload) + var response api_payloads.CreateCustomDimensionResponse + if err := a.PostAndValidate(ctx, api_endpoints.CreateCustomDimension(), request, &response); err != nil { return nil, err } @@ -61,11 +61,11 @@ func (a *CustomDimensionsAPI) Create(ctx context.Context, // Update custom dimension. func (a *CustomDimensionsAPI) Update(ctx context.Context, customDimension models.CustomDimension) (*models.CustomDimension, error) { - payload := payloads.CustomDimensionToPayload(customDimension) + payload := api_payloads.CustomDimensionToPayload(customDimension) - request := payloads.UpdateCustomDimensionRequest(payload) - var response payloads.UpdateCustomDimensionResponse - if err := a.UpdateAndValidate(ctx, endpoints.UpdateCustomDimension(customDimension.ID), request, &response); err != nil { + request := api_payloads.UpdateCustomDimensionRequest(payload) + var response api_payloads.UpdateCustomDimensionResponse + if err := a.UpdateAndValidate(ctx, api_endpoints.UpdateCustomDimension(customDimension.ID), request, &response); err != nil { return nil, err } @@ -75,7 +75,7 @@ func (a *CustomDimensionsAPI) Update(ctx context.Context, // Delete custom dimension. func (a *CustomDimensionsAPI) Delete(ctx context.Context, id models.ID) error { - return a.DeleteAndValidate(ctx, endpoints.DeleteCustomDimension(id), nil) + return a.DeleteAndValidate(ctx, api_endpoints.DeleteCustomDimension(id), nil) } type populatorsAPI struct { @@ -84,11 +84,11 @@ type populatorsAPI struct { // Create new populator. func (a *populatorsAPI) Create(ctx context.Context, populator models.Populator) (*models.Populator, error) { - payload := payloads.PopulatorToPayload(populator) + payload := api_payloads.PopulatorToPayload(populator) - request := payloads.CreatePopulatorRequest{Payload: payload} - var response payloads.CreatePopulatorResponse - if err := a.PostAndValidate(ctx, endpoints.CreatePopulator(populator.DimensionID), request, &response); err != nil { + request := api_payloads.CreatePopulatorRequest{Payload: payload} + var response api_payloads.CreatePopulatorResponse + if err := a.PostAndValidate(ctx, api_endpoints.CreatePopulator(populator.DimensionID), request, &response); err != nil { return nil, err } @@ -98,12 +98,12 @@ func (a *populatorsAPI) Create(ctx context.Context, populator models.Populator) // Update populator. func (a *populatorsAPI) Update(ctx context.Context, populator models.Populator) (*models.Populator, error) { - payload := payloads.PopulatorToPayload(populator) + payload := api_payloads.PopulatorToPayload(populator) - request := payloads.UpdatePopulatorRequest{Payload: payload} - var response payloads.UpdatePopulatorResponse + request := api_payloads.UpdatePopulatorRequest{Payload: payload} + var response api_payloads.UpdatePopulatorResponse if err := a.UpdateAndValidate(ctx, - endpoints.UpdatePopulator(populator.DimensionID, populator.ID), + api_endpoints.UpdatePopulator(populator.DimensionID, populator.ID), request, &response); err != nil { return nil, err @@ -115,5 +115,5 @@ func (a *populatorsAPI) Update(ctx context.Context, populator models.Populator) // Delete populator. func (a *populatorsAPI) Delete(ctx context.Context, dimensionID, populatorID models.ID) error { - return a.DeleteAndValidate(ctx, endpoints.DeletePopulator(dimensionID, populatorID), nil) + return a.DeleteAndValidate(ctx, api_endpoints.DeletePopulator(dimensionID, populatorID), nil) } diff --git a/kentikapi/internal/resources/custom_dimensions_test.go b/kentikapi/internal/resources/custom_dimensions_test.go index 0013777a..b3d52b61 100644 --- a/kentikapi/internal/resources/custom_dimensions_test.go +++ b/kentikapi/internal/resources/custom_dimensions_test.go @@ -7,7 +7,7 @@ import ( "testing" "time" - "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" "github.com/kentik/community_sdk_golang/kentikapi/internal/resources" "github.com/kentik/community_sdk_golang/kentikapi/internal/testutil" "github.com/kentik/community_sdk_golang/kentikapi/internal/utils" @@ -31,7 +31,7 @@ func TestCreateCustomDimension(t *testing.T) { "populators": [] } }` - transport := &connection.StubTransport{ResponseBody: createResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: createResponsePayload} customDimensionsAPI := resources.NewCustomDimensionsAPI(transport) dimension := models.NewCustomDimension( "c_testapi_dimension_1", @@ -78,7 +78,7 @@ func TestUpdateCustomDimension(t *testing.T) { "populators": [] } }` - transport := &connection.StubTransport{ResponseBody: updateResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} customDimensionsAPI := resources.NewCustomDimensionsAPI(transport) dimensionID := models.ID(42) dimension := models.CustomDimension{ID: dimensionID, DisplayName: "dimension_display_name2"} @@ -322,7 +322,7 @@ func TestGetCustomDimension(t *testing.T) { t.Parallel() // arrange - transport := &connection.StubTransport{ResponseBody: tt.responseBody} + transport := &api_connection.StubTransport{ResponseBody: tt.responseBody} customDimensionsAPI := resources.NewCustomDimensionsAPI(transport) dimensionID := 42 @@ -386,7 +386,7 @@ func TestGetAllCustomDimensions(t *testing.T) { } ] }` - transport := &connection.StubTransport{ResponseBody: getResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} customDimensionsAPI := resources.NewCustomDimensionsAPI(transport) // act @@ -435,7 +435,7 @@ func TestDeleteCustomDimension(t *testing.T) { // arrange deleteResponsePayload := "" // deleting device responds with empty body - transport := &connection.StubTransport{ResponseBody: deleteResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} customDimensionsAPI := resources.NewCustomDimensionsAPI(transport) // act @@ -488,7 +488,7 @@ func TestCreatePopulator(t *testing.T) { "updated_date": "2020-12-15T07:55:23.0Z" } }` - transport := &connection.StubTransport{ResponseBody: createResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: createResponsePayload} customDimensionsAPI := resources.NewCustomDimensionsAPI(transport) dimensionID := models.ID(24001) populator := models.NewPopulator( @@ -604,7 +604,7 @@ func TestUpdatePopulator(t *testing.T) { } }` - transport := &connection.StubTransport{ResponseBody: updateResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} customDimensionsAPI := resources.NewCustomDimensionsAPI(transport) dimensionID := models.ID(24001) populatorID := models.ID(1510862280) @@ -664,7 +664,7 @@ func TestDeletePopulator(t *testing.T) { // arrange deleteResponsePayload := "" // deleting device responds with empty body - transport := &connection.StubTransport{ResponseBody: deleteResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} customDimensionsAPI := resources.NewCustomDimensionsAPI(transport) // act diff --git a/kentikapi/internal/resources/device_labels.go b/kentikapi/internal/resources/device_labels.go index ca2aef85..f024688a 100644 --- a/kentikapi/internal/resources/device_labels.go +++ b/kentikapi/internal/resources/device_labels.go @@ -4,9 +4,9 @@ import ( "context" "fmt" - "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/endpoints" - "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_endpoints" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" "github.com/kentik/community_sdk_golang/kentikapi/models" ) @@ -15,7 +15,7 @@ type DeviceLabelsAPI struct { } // NewDeviceLabelsAPI is constructor. -func NewDeviceLabelsAPI(transport connection.Transport) *DeviceLabelsAPI { +func NewDeviceLabelsAPI(transport api_connection.Transport) *DeviceLabelsAPI { return &DeviceLabelsAPI{ BaseAPI{Transport: transport}, } @@ -23,8 +23,8 @@ func NewDeviceLabelsAPI(transport connection.Transport) *DeviceLabelsAPI { // GetAll labels. func (a *DeviceLabelsAPI) GetAll(ctx context.Context) ([]models.DeviceLabel, error) { - var response payloads.GetAllDeviceLabelsResponse - if err := a.GetAndValidate(ctx, endpoints.GetAllLabels(), &response); err != nil { + var response api_payloads.GetAllDeviceLabelsResponse + if err := a.GetAndValidate(ctx, api_endpoints.GetAllLabels(), &response); err != nil { return []models.DeviceLabel{}, err } @@ -33,8 +33,8 @@ func (a *DeviceLabelsAPI) GetAll(ctx context.Context) ([]models.DeviceLabel, err // Get label with given ID. func (a *DeviceLabelsAPI) Get(ctx context.Context, id models.ID) (*models.DeviceLabel, error) { - var response payloads.GetDeviceLabelResponse - if err := a.GetAndValidate(ctx, endpoints.GetLabel(id), &response); err != nil { + var response api_payloads.GetDeviceLabelResponse + if err := a.GetAndValidate(ctx, api_endpoints.GetLabel(id), &response); err != nil { return nil, err } @@ -44,11 +44,11 @@ func (a *DeviceLabelsAPI) Get(ctx context.Context, id models.ID) (*models.Device // Create new label. func (a *DeviceLabelsAPI) Create(ctx context.Context, label models.DeviceLabel) (*models.DeviceLabel, error) { - payload := payloads.DeviceLabelToPayload(label) + payload := api_payloads.DeviceLabelToPayload(label) - request := payloads.CreateDeviceLabelRequest(payload) - var response payloads.CreateDeviceLabelResponse - if err := a.PostAndValidate(ctx, endpoints.CreateLabel(), request, &response); err != nil { + request := api_payloads.CreateDeviceLabelRequest(payload) + var response api_payloads.CreateDeviceLabelResponse + if err := a.PostAndValidate(ctx, api_endpoints.CreateLabel(), request, &response); err != nil { return nil, err } @@ -58,11 +58,11 @@ func (a *DeviceLabelsAPI) Create(ctx context.Context, label models.DeviceLabel) // Update label. func (a *DeviceLabelsAPI) Update(ctx context.Context, label models.DeviceLabel) (*models.DeviceLabel, error) { - payload := payloads.DeviceLabelToPayload(label) + payload := api_payloads.DeviceLabelToPayload(label) - request := payloads.UpdateDeviceLabelRequest(payload) - var response payloads.UpdateDeviceLabelResponse - if err := a.UpdateAndValidate(ctx, endpoints.UpdateLabel(label.ID), request, &response); err != nil { + request := api_payloads.UpdateDeviceLabelRequest(payload) + var response api_payloads.UpdateDeviceLabelResponse + if err := a.UpdateAndValidate(ctx, api_endpoints.UpdateLabel(label.ID), request, &response); err != nil { return nil, err } @@ -72,8 +72,8 @@ func (a *DeviceLabelsAPI) Update(ctx context.Context, label models.DeviceLabel) // Delete label. func (a *DeviceLabelsAPI) Delete(ctx context.Context, id models.ID) error { - var response payloads.DeleteDeviceLabelResponse - if err := a.DeleteAndValidate(ctx, endpoints.DeleteLabel(id), &response); err != nil { + var response api_payloads.DeleteDeviceLabelResponse + if err := a.DeleteAndValidate(ctx, api_endpoints.DeleteLabel(id), &response); err != nil { return err } diff --git a/kentikapi/internal/resources/device_labels_test.go b/kentikapi/internal/resources/device_labels_test.go index 00f36b3f..fb50278b 100644 --- a/kentikapi/internal/resources/device_labels_test.go +++ b/kentikapi/internal/resources/device_labels_test.go @@ -6,7 +6,7 @@ import ( "testing" "time" - "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" "github.com/kentik/community_sdk_golang/kentikapi/internal/resources" "github.com/kentik/community_sdk_golang/kentikapi/internal/utils" "github.com/kentik/community_sdk_golang/kentikapi/models" @@ -30,7 +30,7 @@ func TestCreateDeviceLabel(t *testing.T) { "created_date": "2018-05-16T20:21:10.406Z", "updated_date": "2018-05-16T20:21:10.406Z" }` - transport := &connection.StubTransport{ResponseBody: createResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: createResponsePayload} labelsAPI := resources.NewDeviceLabelsAPI(transport) label := models.NewDeviceLabel("apitest-device_label-1", "#00FF00") @@ -73,7 +73,7 @@ func TestUpdateDeviceLabel(t *testing.T) { "created_date": "2018-05-16T20:21:10.406Z", "updated_date": "2018-06-16T20:21:10.406Z" }` - transport := &connection.StubTransport{ResponseBody: updateResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} labelsAPI := resources.NewDeviceLabelsAPI(transport) label := models.DeviceLabel{Name: "apitest-device_label-one", Color: "#AA00FF"} label.ID = models.ID(42) @@ -124,7 +124,7 @@ func TestGetLabel(t *testing.T) { "created_date": "2018-05-16T20:21:10.406Z", "updated_date": "2018-05-16T20:21:10.406Z" }` - transport := &connection.StubTransport{ResponseBody: getResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} labelsAPI := resources.NewDeviceLabelsAPI(transport) labelID := models.ID(32) @@ -194,7 +194,7 @@ func TestGetAllLabels(t *testing.T) { "updated_date": "2020-11-20T13:45:27.430Z" } ]` - transport := &connection.StubTransport{ResponseBody: getResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} labelsAPI := resources.NewDeviceLabelsAPI(transport) // act @@ -243,7 +243,7 @@ func TestDeleteDeviceLabel(t *testing.T) { { "success": true }` - transport := &connection.StubTransport{ResponseBody: deleteResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} labelsAPI := resources.NewDeviceLabelsAPI(transport) // act diff --git a/kentikapi/internal/resources/devices.go b/kentikapi/internal/resources/devices.go index bf0f6463..cb364861 100644 --- a/kentikapi/internal/resources/devices.go +++ b/kentikapi/internal/resources/devices.go @@ -3,9 +3,9 @@ package resources import ( "context" - "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/endpoints" - "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_endpoints" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" "github.com/kentik/community_sdk_golang/kentikapi/models" ) @@ -15,7 +15,7 @@ type DevicesAPI struct { } // NewDevicesAPI is constructor. -func NewDevicesAPI(transport connection.Transport) *DevicesAPI { +func NewDevicesAPI(transport api_connection.Transport) *DevicesAPI { return &DevicesAPI{ BaseAPI{Transport: transport}, &interfacesAPI{BaseAPI{Transport: transport}}, @@ -24,8 +24,8 @@ func NewDevicesAPI(transport connection.Transport) *DevicesAPI { // GetAll devices. func (a *DevicesAPI) GetAll(ctx context.Context) ([]models.Device, error) { - var response payloads.GetAllDevicesResponse - if err := a.GetAndValidate(ctx, endpoints.DevicesPath, &response); err != nil { + var response api_payloads.GetAllDevicesResponse + if err := a.GetAndValidate(ctx, api_endpoints.DevicesPath, &response); err != nil { return []models.Device{}, err } @@ -34,8 +34,8 @@ func (a *DevicesAPI) GetAll(ctx context.Context) ([]models.Device, error) { // Get device with given ID. func (a *DevicesAPI) Get(ctx context.Context, id models.ID) (*models.Device, error) { - var response payloads.GetDeviceResponse - if err := a.GetAndValidate(ctx, endpoints.GetDevice(id), &response); err != nil { + var response api_payloads.GetDeviceResponse + if err := a.GetAndValidate(ctx, api_endpoints.GetDevice(id), &response); err != nil { return nil, err } @@ -45,9 +45,9 @@ func (a *DevicesAPI) Get(ctx context.Context, id models.ID) (*models.Device, err // Create new device. func (a *DevicesAPI) Create(ctx context.Context, device models.Device) (*models.Device, error) { - request := payloads.CreateDeviceRequest{Payload: payloads.DeviceToPayload(device)} - var response payloads.CreateDeviceResponse - if err := a.PostAndValidate(ctx, endpoints.DevicePath, request, &response); err != nil { + request := api_payloads.CreateDeviceRequest{Payload: api_payloads.DeviceToPayload(device)} + var response api_payloads.CreateDeviceResponse + if err := a.PostAndValidate(ctx, api_endpoints.DevicePath, request, &response); err != nil { return nil, err } @@ -57,9 +57,9 @@ func (a *DevicesAPI) Create(ctx context.Context, device models.Device) (*models. // Update device. func (a *DevicesAPI) Update(ctx context.Context, device models.Device) (*models.Device, error) { - request := payloads.UpdateDeviceRequest{Payload: payloads.DeviceToPayload(device)} - var response payloads.UpdateDeviceResponse - if err := a.UpdateAndValidate(ctx, endpoints.UpdateDevice(device.ID), request, &response); err != nil { + request := api_payloads.UpdateDeviceRequest{Payload: api_payloads.DeviceToPayload(device)} + var response api_payloads.UpdateDeviceResponse + if err := a.UpdateAndValidate(ctx, api_endpoints.UpdateDevice(device.ID), request, &response); err != nil { return nil, err } @@ -71,16 +71,16 @@ func (a *DevicesAPI) Update(ctx context.Context, device models.Device) (*models. // Note: KentikAPI requires sending delete request twice to actually delete the device. // This is a safety measure preventing deletion by mistake. func (a *DevicesAPI) Delete(ctx context.Context, id models.ID) error { - return a.DeleteAndValidate(ctx, endpoints.GetDevice(id), nil) + return a.DeleteAndValidate(ctx, api_endpoints.GetDevice(id), nil) } // ApplyLabels assigns labels to given device. func (a *DevicesAPI) ApplyLabels(ctx context.Context, deviceID models.ID, labels []models.ID) (models.AppliedLabels, error) { - payload := payloads.LabelIDsToPayload(labels) + payload := api_payloads.LabelIDsToPayload(labels) - request := payloads.ApplyLabelsRequest{Labels: payload} - var response payloads.ApplyLabelsResponse - if err := a.UpdateAndValidate(ctx, endpoints.ApplyDeviceLabels(deviceID), request, &response); err != nil { + request := api_payloads.ApplyLabelsRequest{Labels: payload} + var response api_payloads.ApplyLabelsResponse + if err := a.UpdateAndValidate(ctx, api_endpoints.ApplyDeviceLabels(deviceID), request, &response); err != nil { return models.AppliedLabels{}, err } @@ -93,8 +93,8 @@ type interfacesAPI struct { // GetAll interfaces of given device. func (a *interfacesAPI) GetAll(ctx context.Context, deviceID models.ID) ([]models.Interface, error) { - var response payloads.GetAllInterfacesResponse - if err := a.GetAndValidate(ctx, endpoints.GetAllInterfaces(deviceID), &response); err != nil { + var response api_payloads.GetAllInterfacesResponse + if err := a.GetAndValidate(ctx, api_endpoints.GetAllInterfaces(deviceID), &response); err != nil { return nil, err } @@ -103,8 +103,8 @@ func (a *interfacesAPI) GetAll(ctx context.Context, deviceID models.ID) ([]model // Get interface of given device with given ID. func (a *interfacesAPI) Get(ctx context.Context, deviceID, interfaceID models.ID) (*models.Interface, error) { - var response payloads.GetInterfaceResponse - if err := a.GetAndValidate(ctx, endpoints.GetInterface(deviceID, interfaceID), &response); err != nil { + var response api_payloads.GetInterfaceResponse + if err := a.GetAndValidate(ctx, api_endpoints.GetInterface(deviceID, interfaceID), &response); err != nil { return nil, err } @@ -114,14 +114,14 @@ func (a *interfacesAPI) Get(ctx context.Context, deviceID, interfaceID models.ID // Create new interface under given device. func (a *interfacesAPI) Create(ctx context.Context, intf models.Interface) (*models.Interface, error) { - payload, err := payloads.InterfaceToPayload(intf) + payload, err := api_payloads.InterfaceToPayload(intf) if err != nil { return nil, err } - request := payloads.CreateInterfaceRequest(payload) - var response payloads.CreateInterfaceResponse - if err = a.PostAndValidate(ctx, endpoints.CreateInterface(intf.DeviceID), request, &response); err != nil { + request := api_payloads.CreateInterfaceRequest(payload) + var response api_payloads.CreateInterfaceResponse + if err = a.PostAndValidate(ctx, api_endpoints.CreateInterface(intf.DeviceID), request, &response); err != nil { return nil, err } @@ -131,19 +131,19 @@ func (a *interfacesAPI) Create(ctx context.Context, intf models.Interface) (*mod // Delete interface. func (a *interfacesAPI) Delete(ctx context.Context, deviceID, interfaceID models.ID) error { - return a.DeleteAndValidate(ctx, endpoints.DeleteInterface(deviceID, interfaceID), nil) + return a.DeleteAndValidate(ctx, api_endpoints.DeleteInterface(deviceID, interfaceID), nil) } // Update interface. func (a *interfacesAPI) Update(ctx context.Context, intf models.Interface) (*models.Interface, error) { - payload, err := payloads.InterfaceToPayload(intf) + payload, err := api_payloads.InterfaceToPayload(intf) if err != nil { return nil, err } - request := payloads.UpdateInterfaceRequest(payload) - var response payloads.UpdateInterfaceResponse - if err = a.UpdateAndValidate(ctx, endpoints.UpdateInterface(intf.DeviceID, intf.ID), request, &response); err != nil { + request := api_payloads.UpdateInterfaceRequest(payload) + var response api_payloads.UpdateInterfaceResponse + if err = a.UpdateAndValidate(ctx, api_endpoints.UpdateInterface(intf.DeviceID, intf.ID), request, &response); err != nil { return nil, err } diff --git a/kentikapi/internal/resources/devices_test.go b/kentikapi/internal/resources/devices_test.go index cd449454..65470b7c 100644 --- a/kentikapi/internal/resources/devices_test.go +++ b/kentikapi/internal/resources/devices_test.go @@ -8,7 +8,7 @@ import ( "testing" "time" - "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" "github.com/kentik/community_sdk_golang/kentikapi/internal/resources" "github.com/kentik/community_sdk_golang/kentikapi/internal/testutil" "github.com/kentik/community_sdk_golang/kentikapi/internal/utils" @@ -97,7 +97,7 @@ func TestCreateDeviceRouter(t *testing.T) { "device_subtype": "router" } }` - transport := &connection.StubTransport{ResponseBody: createResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: createResponsePayload} devicesAPI := resources.NewDevicesAPI(transport) // act @@ -280,7 +280,7 @@ func TestCreateDeviceDNS(t *testing.T) { "device_subtype": "aws_subnet" } }` - transport := &connection.StubTransport{ResponseBody: createResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: createResponsePayload} devicesAPI := resources.NewDevicesAPI(transport) // act @@ -445,7 +445,7 @@ func TestUpdatetDeviceRouter(t *testing.T) { "device_subtype": "paloalto" } }` - transport := &connection.StubTransport{ResponseBody: updateResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} devicesAPI := resources.NewDevicesAPI(transport) // act @@ -1093,7 +1093,7 @@ func TestGetDevice(t *testing.T) { t.Parallel() // arrange - transport := &connection.StubTransport{ResponseBody: tt.responseBody} + transport := &api_connection.StubTransport{ResponseBody: tt.responseBody} devicesAPI := resources.NewDevicesAPI(transport) deviceID := 43 @@ -1290,7 +1290,7 @@ func TestGetAllDevices(t *testing.T) { } ] }` - transport := &connection.StubTransport{ResponseBody: getResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} devicesAPI := resources.NewDevicesAPI(transport) // act @@ -1393,7 +1393,7 @@ func TestDeleteDevice(t *testing.T) { // arrange deleteResponsePayload := "" // deleting device responds with empty body - transport := &connection.StubTransport{ResponseBody: deleteResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} devicesAPI := resources.NewDevicesAPI(transport) // act @@ -1446,7 +1446,7 @@ func TestApplyLabels(t *testing.T) { } ] }` - transport := &connection.StubTransport{ResponseBody: applyLabelsResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: applyLabelsResponsePayload} devicesAPI := resources.NewDevicesAPI(transport) // act @@ -1517,7 +1517,7 @@ func TestGetInterfaceMinimal(t *testing.T) { "secondary_ips": null } }` - transport := &connection.StubTransport{ResponseBody: getResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} devicesAPI := resources.NewDevicesAPI(transport) // act @@ -1622,7 +1622,7 @@ func TestGetInterfaceFull(t *testing.T) { ] } }` - transport := &connection.StubTransport{ResponseBody: getResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} devicesAPI := resources.NewDevicesAPI(transport) // act @@ -1812,7 +1812,7 @@ func TestGetAllInterfaces(t *testing.T) { "vrf": {} } ]` - transport := &connection.StubTransport{ResponseBody: getResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} devicesAPI := resources.NewDevicesAPI(transport) // act @@ -1882,7 +1882,7 @@ func TestCreateInterfaceMinimal(t *testing.T) { "cdate": "2021-01-13T08:41:16.191Z", "id": "43" }` - transport := &connection.StubTransport{ResponseBody: getResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} devicesAPI := resources.NewDevicesAPI(transport) // act @@ -1953,7 +1953,7 @@ func TestCreateInterfaceFull(t *testing.T) { } ] }` - transport := &connection.StubTransport{ResponseBody: getResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} devicesAPI := resources.NewDevicesAPI(transport) // act @@ -2030,7 +2030,7 @@ func TestDeleteInterface(t *testing.T) { // arrange deleteResponsePayload := "{}" - transport := &connection.StubTransport{ResponseBody: deleteResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} devicesAPI := resources.NewDevicesAPI(transport) // act @@ -2083,7 +2083,7 @@ func TestUpdateInterfaceMinimal(t *testing.T) { "initial_interface_ip": null, "initial_interface_ip_netmask": null }` - transport := &connection.StubTransport{ResponseBody: updateResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} devicesAPI := resources.NewDevicesAPI(transport) // act @@ -2162,7 +2162,7 @@ func TestUpdateInterfaceFull(t *testing.T) { "initial_interface_ip": null, "initial_interface_ip_netmask": null }` - transport := &connection.StubTransport{ResponseBody: updateResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} devicesAPI := resources.NewDevicesAPI(transport) // act diff --git a/kentikapi/internal/resources/my_kentik_portal.go b/kentikapi/internal/resources/my_kentik_portal.go index 68fbdd3c..58bb9aaa 100644 --- a/kentikapi/internal/resources/my_kentik_portal.go +++ b/kentikapi/internal/resources/my_kentik_portal.go @@ -3,9 +3,9 @@ package resources import ( "context" - "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/endpoints" - "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_endpoints" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" "github.com/kentik/community_sdk_golang/kentikapi/models" ) @@ -13,14 +13,14 @@ type MyKentikPortalAPI struct { BaseAPI } -func NewMyKentikPortalAPI(transport connection.Transport) *MyKentikPortalAPI { +func NewMyKentikPortalAPI(transport api_connection.Transport) *MyKentikPortalAPI { return &MyKentikPortalAPI{BaseAPI{Transport: transport}} } // GetAll lists all tenants. func (a *MyKentikPortalAPI) GetAll(ctx context.Context) ([]models.Tenant, error) { - var response payloads.GetAllTenantsResponse - if err := a.GetAndValidate(ctx, endpoints.TenantsPath, &response); err != nil { + var response api_payloads.GetAllTenantsResponse + if err := a.GetAndValidate(ctx, api_endpoints.TenantsPath, &response); err != nil { return []models.Tenant{}, err } @@ -29,8 +29,8 @@ func (a *MyKentikPortalAPI) GetAll(ctx context.Context) ([]models.Tenant, error) // Get Tenant Info. func (a *MyKentikPortalAPI) Get(ctx context.Context, tenantID models.ID) (*models.Tenant, error) { - var response payloads.TenantPayload - if err := a.GetAndValidate(ctx, endpoints.GetTenantPath(tenantID), &response); err != nil { + var response api_payloads.TenantPayload + if err := a.GetAndValidate(ctx, api_endpoints.GetTenantPath(tenantID), &response); err != nil { return nil, err } tenant, err := response.ToTenant() @@ -39,13 +39,13 @@ func (a *MyKentikPortalAPI) Get(ctx context.Context, tenantID models.ID) (*model func (a *MyKentikPortalAPI) CreateTenantUser(ctx context.Context, tenantID models.ID, userEmail string) (*models.TenantUser, error) { - request := payloads.CreateTenantUserRequest{ - User: payloads.CreateTenantUserPayload{ + request := api_payloads.CreateTenantUserRequest{ + User: api_payloads.CreateTenantUserPayload{ Email: userEmail, }, } - var response payloads.TenantUserPayload - if err := a.PostAndValidate(ctx, endpoints.CreateTenantUserPath(tenantID), request, &response); err != nil { + var response api_payloads.TenantUserPayload + if err := a.PostAndValidate(ctx, api_endpoints.CreateTenantUserPath(tenantID), request, &response); err != nil { return nil, err } @@ -54,7 +54,7 @@ func (a *MyKentikPortalAPI) CreateTenantUser(ctx context.Context, } func (a *MyKentikPortalAPI) DeleteTenantUser(ctx context.Context, tenantID models.ID, userID models.ID) error { - if err := a.DeleteAndValidate(ctx, endpoints.DeleteTenantUserPath(tenantID, userID), nil); err != nil { + if err := a.DeleteAndValidate(ctx, api_endpoints.DeleteTenantUserPath(tenantID, userID), nil); err != nil { return err } diff --git a/kentikapi/internal/resources/my_kentik_portal_test.go b/kentikapi/internal/resources/my_kentik_portal_test.go index 846b4f69..6dd54f7f 100644 --- a/kentikapi/internal/resources/my_kentik_portal_test.go +++ b/kentikapi/internal/resources/my_kentik_portal_test.go @@ -5,7 +5,7 @@ import ( "testing" "time" - "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" "github.com/kentik/community_sdk_golang/kentikapi/internal/resources" "github.com/kentik/community_sdk_golang/kentikapi/internal/utils" "github.com/kentik/community_sdk_golang/kentikapi/models" @@ -85,7 +85,7 @@ func TestTenantsList(t *testing.T) { }, } - transport := &connection.StubTransport{ResponseBody: getAllResponse} + transport := &api_connection.StubTransport{ResponseBody: getAllResponse} myKentikPortalAPI := resources.NewMyKentikPortalAPI(transport) // act @@ -153,7 +153,7 @@ func TestGetTenantInfo(t *testing.T) { }, } - transport := &connection.StubTransport{ResponseBody: getTenantInfoResponse} + transport := &api_connection.StubTransport{ResponseBody: getTenantInfoResponse} myKentikPortalAPI := resources.NewMyKentikPortalAPI(transport) // act @@ -187,7 +187,7 @@ func TestTenantUserCreate(t *testing.T) { CompanyID: 74333, } - transport := &connection.StubTransport{ResponseBody: createTenantUserResponse} + transport := &api_connection.StubTransport{ResponseBody: createTenantUserResponse} myKentikPortalAPI := resources.NewMyKentikPortalAPI(transport) // act @@ -210,7 +210,7 @@ func TestTenantUserDelete(t *testing.T) { // arrange deleteResponsePayload := "" - transport := &connection.StubTransport{ResponseBody: deleteResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} myKentikPortalAPI := resources.NewMyKentikPortalAPI(transport) // act diff --git a/kentikapi/internal/resources/plans.go b/kentikapi/internal/resources/plans.go index 47aeabb0..3ecc3406 100644 --- a/kentikapi/internal/resources/plans.go +++ b/kentikapi/internal/resources/plans.go @@ -3,9 +3,9 @@ package resources import ( "context" - "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/endpoints" - "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_endpoints" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" "github.com/kentik/community_sdk_golang/kentikapi/models" ) @@ -14,7 +14,7 @@ type PlansAPI struct { } // NewPlansAPI is constructor. -func NewPlansAPI(transport connection.Transport) *PlansAPI { +func NewPlansAPI(transport api_connection.Transport) *PlansAPI { return &PlansAPI{ BaseAPI{Transport: transport}, } @@ -22,8 +22,8 @@ func NewPlansAPI(transport connection.Transport) *PlansAPI { // GetAll plans. func (a *PlansAPI) GetAll(ctx context.Context) ([]models.Plan, error) { - var response payloads.GetAllPlansResponse - if err := a.GetAndValidate(ctx, endpoints.GetAllPlans(), &response); err != nil { + var response api_payloads.GetAllPlansResponse + if err := a.GetAndValidate(ctx, api_endpoints.GetAllPlans(), &response); err != nil { return []models.Plan{}, err } diff --git a/kentikapi/internal/resources/plans_test.go b/kentikapi/internal/resources/plans_test.go index 9f600008..07dbd657 100644 --- a/kentikapi/internal/resources/plans_test.go +++ b/kentikapi/internal/resources/plans_test.go @@ -4,7 +4,7 @@ import ( "context" "testing" - "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" "github.com/kentik/community_sdk_golang/kentikapi/internal/resources" "github.com/kentik/community_sdk_golang/kentikapi/models" "github.com/stretchr/testify/assert" @@ -67,7 +67,7 @@ func TestGetAllPlans(t *testing.T) { } ] }` - transport := &connection.StubTransport{ResponseBody: getResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} plansAPI := resources.NewPlansAPI(transport) // act diff --git a/kentikapi/internal/resources/query.go b/kentikapi/internal/resources/query.go index 4eaa56c4..67a3e2d4 100644 --- a/kentikapi/internal/resources/query.go +++ b/kentikapi/internal/resources/query.go @@ -3,9 +3,9 @@ package resources import ( "context" - "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/endpoints" - "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_endpoints" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" "github.com/kentik/community_sdk_golang/kentikapi/models" ) @@ -14,7 +14,7 @@ type QueryAPI struct { } // NewQueryAPI is constructor. -func NewQueryAPI(transport connection.Transport) *QueryAPI { +func NewQueryAPI(transport api_connection.Transport) *QueryAPI { return &QueryAPI{ BaseAPI{Transport: transport}, } @@ -22,10 +22,10 @@ func NewQueryAPI(transport connection.Transport) *QueryAPI { // SQL query. func (a *QueryAPI) SQL(ctx context.Context, sql string) (models.QuerySQLResult, error) { - payload := payloads.QuerySQLRequest{Query: sql} + payload := api_payloads.QuerySQLRequest{Query: sql} - var response payloads.QuerySQLResponse - if err := a.PostAndValidate(ctx, endpoints.QuerySQL(), payload, &response); err != nil { + var response api_payloads.QuerySQLResponse + if err := a.PostAndValidate(ctx, api_endpoints.QuerySQL(), payload, &response); err != nil { return models.QuerySQLResult{}, err } @@ -34,13 +34,13 @@ func (a *QueryAPI) SQL(ctx context.Context, sql string) (models.QuerySQLResult, // Data query. func (a *QueryAPI) Data(ctx context.Context, query models.QueryObject) (models.QueryDataResult, error) { - payload, err := payloads.QueryObjectToPayload(query) + payload, err := api_payloads.QueryObjectToPayload(query) if err != nil { return models.QueryDataResult{}, err } - var response payloads.QueryDataResponse - if err := a.PostAndValidate(ctx, endpoints.QueryData(), payload, &response); err != nil { + var response api_payloads.QueryDataResponse + if err := a.PostAndValidate(ctx, api_endpoints.QueryData(), payload, &response); err != nil { return models.QueryDataResult{}, err } @@ -49,13 +49,13 @@ func (a *QueryAPI) Data(ctx context.Context, query models.QueryObject) (models.Q // Chart query. func (a *QueryAPI) Chart(ctx context.Context, query models.QueryObject) (models.QueryChartResult, error) { - payload, err := payloads.QueryObjectToPayload(query) + payload, err := api_payloads.QueryObjectToPayload(query) if err != nil { return models.QueryChartResult{}, err } - var response payloads.QueryChartResponse - if err := a.PostAndValidate(ctx, endpoints.QueryChart(), payload, &response); err != nil { + var response api_payloads.QueryChartResponse + if err := a.PostAndValidate(ctx, api_endpoints.QueryChart(), payload, &response); err != nil { return models.QueryChartResult{}, err } @@ -64,13 +64,13 @@ func (a *QueryAPI) Chart(ctx context.Context, query models.QueryObject) (models. // URL query. func (a *QueryAPI) URL(ctx context.Context, query models.QueryObject) (models.QueryURLResult, error) { - payload, err := payloads.QueryObjectToPayload(query) + payload, err := api_payloads.QueryObjectToPayload(query) if err != nil { return models.QueryURLResult{}, err } - var response payloads.QueryURLResponse - if err := a.PostAndValidate(ctx, endpoints.QueryURL(), payload, &response); err != nil { + var response api_payloads.QueryURLResponse + if err := a.PostAndValidate(ctx, api_endpoints.QueryURL(), payload, &response); err != nil { return models.QueryURLResult{}, err } diff --git a/kentikapi/internal/resources/query_test.go b/kentikapi/internal/resources/query_test.go index 388ea306..b525bef3 100644 --- a/kentikapi/internal/resources/query_test.go +++ b/kentikapi/internal/resources/query_test.go @@ -6,7 +6,7 @@ import ( "testing" "time" - "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" "github.com/kentik/community_sdk_golang/kentikapi/internal/resources" "github.com/kentik/community_sdk_golang/kentikapi/internal/utils" "github.com/kentik/community_sdk_golang/kentikapi/models" @@ -49,7 +49,7 @@ func TestQuerySQL(t *testing.T) { } ] }` - transport := &connection.StubTransport{ResponseBody: queryResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: queryResponsePayload} queryAPI := resources.NewQueryAPI(transport) // act @@ -127,7 +127,7 @@ func TestQueryData(t *testing.T) { } ] }` - transport := &connection.StubTransport{ResponseBody: queryResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: queryResponsePayload} queryAPI := resources.NewQueryAPI(transport) agg1 := models.Aggregate{ @@ -222,7 +222,7 @@ func TestQueryChart(t *testing.T) { // arrange data := "ImageDataEncodedBase64==" queryResponsePayload := `{"dataUri": "data:image/png;base64,ImageDataEncodedBase64=="}` - transport := &connection.StubTransport{ResponseBody: queryResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: queryResponsePayload} queryAPI := resources.NewQueryAPI(transport) agg1 := models.Aggregate{ @@ -366,7 +366,7 @@ func TestQueryURL(t *testing.T) { // arrange unquotedResponse := "https://portal.kentik.com/portal/#Charts/shortUrl/e0d24b3cc8dfe41f9093668e531cbe96" queryResponsePayload := `"` + unquotedResponse + `"` // actual response is url in quotation marks - transport := &connection.StubTransport{ResponseBody: queryResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: queryResponsePayload} queryAPI := resources.NewQueryAPI(transport) agg1 := models.Aggregate{Name: "avg_bits_per_sec", Column: "f_sum_both_bytes", Fn: models.AggregateFunctionTypeAverage} diff --git a/kentikapi/internal/resources/saved_filters.go b/kentikapi/internal/resources/saved_filters.go index 17cad6f0..f1bb8ef9 100644 --- a/kentikapi/internal/resources/saved_filters.go +++ b/kentikapi/internal/resources/saved_filters.go @@ -3,9 +3,9 @@ package resources import ( "context" - "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/endpoints" - "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_endpoints" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" "github.com/kentik/community_sdk_golang/kentikapi/models" ) @@ -13,13 +13,13 @@ type SavedFiltersAPI struct { BaseAPI } -func NewSavedFiltersAPI(transport connection.Transport) *SavedFiltersAPI { +func NewSavedFiltersAPI(transport api_connection.Transport) *SavedFiltersAPI { return &SavedFiltersAPI{BaseAPI{Transport: transport}} } func (a *SavedFiltersAPI) GetAll(ctx context.Context) ([]models.SavedFilter, error) { - var response payloads.GetAllSavedFilterResponse - if err := a.GetAndValidate(ctx, endpoints.SavedFiltersPath, &response); err != nil { + var response api_payloads.GetAllSavedFilterResponse + if err := a.GetAndValidate(ctx, api_endpoints.SavedFiltersPath, &response); err != nil { return nil, err } @@ -27,8 +27,8 @@ func (a *SavedFiltersAPI) GetAll(ctx context.Context) ([]models.SavedFilter, err } func (a *SavedFiltersAPI) Get(ctx context.Context, filterID models.ID) (*models.SavedFilter, error) { - var response payloads.GetSavedFilterResponse - err := a.GetAndValidate(ctx, endpoints.GetSavedFilter(filterID), &response) + var response api_payloads.GetSavedFilterResponse + err := a.GetAndValidate(ctx, api_endpoints.GetSavedFilter(filterID), &response) if err != nil { return nil, err } @@ -39,10 +39,10 @@ func (a *SavedFiltersAPI) Get(ctx context.Context, filterID models.ID) (*models. } func (a *SavedFiltersAPI) Create(ctx context.Context, savedFilter models.SavedFilter) (*models.SavedFilter, error) { - payload := payloads.SavedFilterToCreatePayload(savedFilter) + payload := api_payloads.SavedFilterToCreatePayload(savedFilter) - var response payloads.CreateSavedFilterResponse - if err := a.PostAndValidate(ctx, endpoints.SavedFilterPath, payload, &response); err != nil { + var response api_payloads.CreateSavedFilterResponse + if err := a.PostAndValidate(ctx, api_endpoints.SavedFilterPath, payload, &response); err != nil { return nil, err } @@ -51,10 +51,10 @@ func (a *SavedFiltersAPI) Create(ctx context.Context, savedFilter models.SavedFi } func (a *SavedFiltersAPI) Update(ctx context.Context, savedFilter models.SavedFilter) (*models.SavedFilter, error) { - payload := payloads.SavedFilterToUpdatePayload(savedFilter) + payload := api_payloads.SavedFilterToUpdatePayload(savedFilter) - var response payloads.UpdateSavedFilterResponse - if err := a.UpdateAndValidate(ctx, endpoints.GetSavedFilter(savedFilter.ID), payload, &response); err != nil { + var response api_payloads.UpdateSavedFilterResponse + if err := a.UpdateAndValidate(ctx, api_endpoints.GetSavedFilter(savedFilter.ID), payload, &response); err != nil { return nil, err } @@ -63,5 +63,5 @@ func (a *SavedFiltersAPI) Update(ctx context.Context, savedFilter models.SavedFi } func (a *SavedFiltersAPI) Detete(ctx context.Context, id models.ID) error { - return a.DeleteAndValidate(ctx, endpoints.GetSavedFilter(id), nil) + return a.DeleteAndValidate(ctx, api_endpoints.GetSavedFilter(id), nil) } diff --git a/kentikapi/internal/resources/saved_filters_test.go b/kentikapi/internal/resources/saved_filters_test.go index 9ef95a1f..e21f5ba1 100644 --- a/kentikapi/internal/resources/saved_filters_test.go +++ b/kentikapi/internal/resources/saved_filters_test.go @@ -5,7 +5,7 @@ import ( "testing" "time" - "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" "github.com/kentik/community_sdk_golang/kentikapi/internal/resources" "github.com/kentik/community_sdk_golang/kentikapi/models" "github.com/stretchr/testify/assert" @@ -126,7 +126,7 @@ func TestSavedFiltersList(t *testing.T) { }, } - transport := &connection.StubTransport{ResponseBody: getAllresponsePayload} + transport := &api_connection.StubTransport{ResponseBody: getAllresponsePayload} savedFiltersAPI := resources.NewSavedFiltersAPI(transport) savedFilters, err := savedFiltersAPI.GetAll(context.Background()) @@ -192,7 +192,7 @@ func TestGetSavedFilterInfo(t *testing.T) { FilterLevel: "company", } - transport := &connection.StubTransport{ResponseBody: getResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} savedFiltersAPI := resources.NewSavedFiltersAPI(transport) savedFilter, err := savedFiltersAPI.Get(context.Background(), 8275) @@ -262,7 +262,7 @@ func TestCreateSavedFilter(t *testing.T) { "\"filterGroups\":[{\"connector\":\"All\",\"not\":false,\"filters\":[{\"filterField\":\"dst_as\"," + "\"filterValue\":\"81\",\"operator\":\"=\"}]}]}}" - transport := &connection.StubTransport{ResponseBody: postResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: postResponsePayload} savedFiltersAPI := resources.NewSavedFiltersAPI(transport) newSavedFilter := models.SavedFilter{ @@ -325,7 +325,7 @@ func TestUpdateSavedFilter(t *testing.T) { "\"filterGroups\":[{\"connector\":\"All\",\"not\":false,\"filters\":[{\"filterField\":\"dst_as\"," + "\"filterValue\":\"81\",\"operator\":\"=\"}]}]}}" - transport := &connection.StubTransport{ResponseBody: updateResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} savedFiltersAPI := resources.NewSavedFiltersAPI(transport) filterID := 8153 @@ -363,7 +363,7 @@ func TestDeleteSavedFilter(t *testing.T) { deleteResponsePayload := "" - transport := &connection.StubTransport{ResponseBody: deleteResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} savedFiltersAPI := resources.NewSavedFiltersAPI(transport) filterID := 8153 diff --git a/kentikapi/internal/resources/sites.go b/kentikapi/internal/resources/sites.go index 80bce688..a88fdae3 100644 --- a/kentikapi/internal/resources/sites.go +++ b/kentikapi/internal/resources/sites.go @@ -3,9 +3,9 @@ package resources import ( "context" - "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/endpoints" - "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_endpoints" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" "github.com/kentik/community_sdk_golang/kentikapi/models" ) @@ -14,7 +14,7 @@ type SitesAPI struct { } // NewSitesAPI is constructor. -func NewSitesAPI(transport connection.Transport) *SitesAPI { +func NewSitesAPI(transport api_connection.Transport) *SitesAPI { return &SitesAPI{ BaseAPI{Transport: transport}, } @@ -22,8 +22,8 @@ func NewSitesAPI(transport connection.Transport) *SitesAPI { // GetAll sites. func (a *SitesAPI) GetAll(ctx context.Context) ([]models.Site, error) { - var response payloads.GetAllSitesResponse - if err := a.GetAndValidate(ctx, endpoints.GetAllSites(), &response); err != nil { + var response api_payloads.GetAllSitesResponse + if err := a.GetAndValidate(ctx, api_endpoints.GetAllSites(), &response); err != nil { return []models.Site{}, err } @@ -32,8 +32,8 @@ func (a *SitesAPI) GetAll(ctx context.Context) ([]models.Site, error) { // Get site with given ID. func (a *SitesAPI) Get(ctx context.Context, id models.ID) (*models.Site, error) { - var response payloads.GetSiteResponse - if err := a.GetAndValidate(ctx, endpoints.GetSite(id), &response); err != nil { + var response api_payloads.GetSiteResponse + if err := a.GetAndValidate(ctx, api_endpoints.GetSite(id), &response); err != nil { return nil, err } @@ -43,14 +43,14 @@ func (a *SitesAPI) Get(ctx context.Context, id models.ID) (*models.Site, error) // Create new site. func (a *SitesAPI) Create(ctx context.Context, site models.Site) (*models.Site, error) { - payload, err := payloads.SiteToPayload(site) + payload, err := api_payloads.SiteToPayload(site) if err != nil { return nil, err } - request := payloads.CreateSiteRequest{Payload: payload} - var response payloads.CreateSiteResponse - if err = a.PostAndValidate(ctx, endpoints.CreateSite(), request, &response); err != nil { + request := api_payloads.CreateSiteRequest{Payload: payload} + var response api_payloads.CreateSiteResponse + if err = a.PostAndValidate(ctx, api_endpoints.CreateSite(), request, &response); err != nil { return nil, err } @@ -60,14 +60,14 @@ func (a *SitesAPI) Create(ctx context.Context, site models.Site) (*models.Site, // Update site. func (a *SitesAPI) Update(ctx context.Context, site models.Site) (*models.Site, error) { - payload, err := payloads.SiteToPayload(site) + payload, err := api_payloads.SiteToPayload(site) if err != nil { return nil, err } - request := payloads.UpdateSiteRequest{Payload: payload} - var response payloads.UpdateSiteResponse - if err = a.UpdateAndValidate(ctx, endpoints.UpdateSite(site.ID), request, &response); err != nil { + request := api_payloads.UpdateSiteRequest{Payload: payload} + var response api_payloads.UpdateSiteResponse + if err = a.UpdateAndValidate(ctx, api_endpoints.UpdateSite(site.ID), request, &response); err != nil { return nil, err } @@ -77,7 +77,7 @@ func (a *SitesAPI) Update(ctx context.Context, site models.Site) (*models.Site, // Delete site. func (a *SitesAPI) Delete(ctx context.Context, id models.ID) error { - if err := a.DeleteAndValidate(ctx, endpoints.DeleteSite(id), nil); err != nil { + if err := a.DeleteAndValidate(ctx, api_endpoints.DeleteSite(id), nil); err != nil { return err } diff --git a/kentikapi/internal/resources/sites_test.go b/kentikapi/internal/resources/sites_test.go index 92ba55b3..ea54eb5a 100644 --- a/kentikapi/internal/resources/sites_test.go +++ b/kentikapi/internal/resources/sites_test.go @@ -4,7 +4,7 @@ import ( "context" "testing" - "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" "github.com/kentik/community_sdk_golang/kentikapi/internal/resources" "github.com/kentik/community_sdk_golang/kentikapi/internal/utils" "github.com/kentik/community_sdk_golang/kentikapi/models" @@ -26,7 +26,7 @@ func TestGetSite(t *testing.T) { "company_id": 3250 } }` - transport := &connection.StubTransport{ResponseBody: getResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} sitesAPI := resources.NewSitesAPI(transport) siteID := models.ID(42) @@ -78,7 +78,7 @@ func TestGetAllSites(t *testing.T) { } ] }` - transport := &connection.StubTransport{ResponseBody: getResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} sitesAPI := resources.NewSitesAPI(transport) // act @@ -130,7 +130,7 @@ func TestCreateSite(t *testing.T) { "company_id": "3250" } }` - transport := &connection.StubTransport{ResponseBody: createResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: createResponsePayload} sitesAPI := resources.NewSitesAPI(transport) // act @@ -172,7 +172,7 @@ func TestUpdateSite(t *testing.T) { "company_id": "3250" } }` - transport := &connection.StubTransport{ResponseBody: updateResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} sitesAPI := resources.NewSitesAPI(transport) // act @@ -205,7 +205,7 @@ func TestDeleteSite(t *testing.T) { // arrange deleteResponsePayload := "" // deleting site responds with empty body - transport := &connection.StubTransport{ResponseBody: deleteResponsePayload} + transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} sitesAPI := resources.NewSitesAPI(transport) // act diff --git a/kentikapi/internal/resources/tags.go b/kentikapi/internal/resources/tags.go index ba149748..9878face 100644 --- a/kentikapi/internal/resources/tags.go +++ b/kentikapi/internal/resources/tags.go @@ -4,9 +4,9 @@ package resources import ( "context" - "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/endpoints" - "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_endpoints" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" "github.com/kentik/community_sdk_golang/kentikapi/models" ) @@ -16,14 +16,14 @@ type TagsAPI struct { } // NewTagsAPI creates new TagsAPI. -func NewTagsAPI(transport connection.Transport) *TagsAPI { +func NewTagsAPI(transport api_connection.Transport) *TagsAPI { return &TagsAPI{BaseAPI{Transport: transport}} } // GetAll lists tags. func (a *TagsAPI) GetAll(ctx context.Context) ([]models.Tag, error) { - var response payloads.GetAllTagsResponse - if err := a.GetAndValidate(ctx, endpoints.TagsPath, &response); err != nil { + var response api_payloads.GetAllTagsResponse + if err := a.GetAndValidate(ctx, api_endpoints.TagsPath, &response); err != nil { return nil, err } @@ -32,8 +32,8 @@ func (a *TagsAPI) GetAll(ctx context.Context) ([]models.Tag, error) { // Get retrieves tag with given ID. func (a *TagsAPI) Get(ctx context.Context, id models.ID) (*models.Tag, error) { - var response payloads.GetTagResponse - if err := a.GetAndValidate(ctx, endpoints.GetTagPath(id), &response); err != nil { + var response api_payloads.GetTagResponse + if err := a.GetAndValidate(ctx, api_endpoints.GetTagPath(id), &response); err != nil { return nil, err } @@ -42,11 +42,11 @@ func (a *TagsAPI) Get(ctx context.Context, id models.ID) (*models.Tag, error) { // Create creates new tag. func (a *TagsAPI) Create(ctx context.Context, tag models.Tag) (*models.Tag, error) { - var response payloads.CreateTagResponse + var response api_payloads.CreateTagResponse err := a.PostAndValidate( ctx, - endpoints.TagPath, - payloads.CreateTagRequest{Tag: payloads.TagToPayload(tag)}, + api_endpoints.TagPath, + api_payloads.CreateTagRequest{Tag: api_payloads.TagToPayload(tag)}, &response, ) if err != nil { @@ -58,11 +58,11 @@ func (a *TagsAPI) Create(ctx context.Context, tag models.Tag) (*models.Tag, erro // Update updates the tag. func (a *TagsAPI) Update(ctx context.Context, tag models.Tag) (*models.Tag, error) { - var response payloads.UpdateTagResponse + var response api_payloads.UpdateTagResponse err := a.UpdateAndValidate( ctx, - endpoints.GetTagPath(tag.ID), - payloads.UpdateTagRequest{Tag: payloads.TagToPayload(tag)}, + api_endpoints.GetTagPath(tag.ID), + api_payloads.UpdateTagRequest{Tag: api_payloads.TagToPayload(tag)}, &response, ) if err != nil { @@ -74,7 +74,7 @@ func (a *TagsAPI) Update(ctx context.Context, tag models.Tag) (*models.Tag, erro // Delete removes tag with given ID. func (a *TagsAPI) Delete(ctx context.Context, id models.ID) error { - if err := a.DeleteAndValidate(ctx, endpoints.GetTagPath(id), nil); err != nil { + if err := a.DeleteAndValidate(ctx, api_endpoints.GetTagPath(id), nil); err != nil { return err } diff --git a/kentikapi/internal/resources/users.go b/kentikapi/internal/resources/users.go index b1b48b20..2fae0eb6 100644 --- a/kentikapi/internal/resources/users.go +++ b/kentikapi/internal/resources/users.go @@ -4,9 +4,9 @@ package resources import ( "context" - "github.com/kentik/community_sdk_golang/kentikapi/internal/connection" - "github.com/kentik/community_sdk_golang/kentikapi/internal/endpoints" - "github.com/kentik/community_sdk_golang/kentikapi/internal/payloads" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_connection" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_endpoints" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" "github.com/kentik/community_sdk_golang/kentikapi/models" ) @@ -16,14 +16,14 @@ type UsersAPI struct { } // NewUsersAPI creates new UsersAPI. -func NewUsersAPI(transport connection.Transport) *UsersAPI { +func NewUsersAPI(transport api_connection.Transport) *UsersAPI { return &UsersAPI{BaseAPI{Transport: transport}} } // GetAll lists users. func (a *UsersAPI) GetAll(ctx context.Context) ([]models.User, error) { - var response payloads.GetAllUsersResponse - if err := a.GetAndValidate(ctx, endpoints.UsersPath, &response); err != nil { + var response api_payloads.GetAllUsersResponse + if err := a.GetAndValidate(ctx, api_endpoints.UsersPath, &response); err != nil { return nil, err } @@ -32,8 +32,8 @@ func (a *UsersAPI) GetAll(ctx context.Context) ([]models.User, error) { // Get retrieves user with given ID. func (a *UsersAPI) Get(ctx context.Context, id models.ID) (*models.User, error) { - var response payloads.GetUserResponse - if err := a.GetAndValidate(ctx, endpoints.GetUserPath(id), &response); err != nil { + var response api_payloads.GetUserResponse + if err := a.GetAndValidate(ctx, api_endpoints.GetUserPath(id), &response); err != nil { return nil, err } @@ -42,11 +42,11 @@ func (a *UsersAPI) Get(ctx context.Context, id models.ID) (*models.User, error) // Create creates new user. func (a *UsersAPI) Create(ctx context.Context, user models.User) (*models.User, error) { - var response payloads.CreateUserResponse + var response api_payloads.CreateUserResponse err := a.PostAndValidate( ctx, - endpoints.UserPath, - payloads.CreateUserRequest{User: payloads.UserToPayload(user)}, + api_endpoints.UserPath, + api_payloads.CreateUserRequest{User: api_payloads.UserToPayload(user)}, &response, ) if err != nil { @@ -58,11 +58,11 @@ func (a *UsersAPI) Create(ctx context.Context, user models.User) (*models.User, // Update updates the user. func (a *UsersAPI) Update(ctx context.Context, user models.User) (*models.User, error) { - var response payloads.UpdateUserResponse + var response api_payloads.UpdateUserResponse err := a.UpdateAndValidate( ctx, - endpoints.GetUserPath(user.ID), - payloads.UpdateUserRequest{User: payloads.UserToPayload(user)}, + api_endpoints.GetUserPath(user.ID), + api_payloads.UpdateUserRequest{User: api_payloads.UserToPayload(user)}, &response, ) if err != nil { @@ -74,7 +74,7 @@ func (a *UsersAPI) Update(ctx context.Context, user models.User) (*models.User, // Delete removes user with given ID. func (a *UsersAPI) Delete(ctx context.Context, id models.ID) error { - if err := a.DeleteAndValidate(ctx, endpoints.GetUserPath(id), nil); err != nil { + if err := a.DeleteAndValidate(ctx, api_endpoints.GetUserPath(id), nil); err != nil { return err } From 4d88ebf0d5a8cb079b291c6035118f2ff3c6e1b4 Mon Sep 17 00:00:00 2001 From: maciej palczynski Date: Thu, 9 Sep 2021 13:43:33 +0200 Subject: [PATCH 3/6] Implemented first batch of suggestions from review --- .golangci.yml | 26 ++++++--------- apiv6/examples/cloud_export/main.go | 10 +++--- .../examples/demos/cloud_export_demo/main.go | 10 +++--- apiv6/examples/demos/retry_demo/main.go | 2 +- apiv6/examples/synthetics/main.go | 24 +++++++------- apiv6/examples/synthetics/mesh_test/main.go | 2 +- apiv6/kentikapi/client.go | 13 ++++---- apiv6/kentikapi/client_integration_test.go | 9 ++--- apiv6/kentikapi/httputil/httputil_test.go | 21 ++---------- examples/custom_applications_example_test.go | 2 -- kentikapi/internal/api_payloads/query_test.go | 16 --------- kentikapi/internal/api_payloads/types_test.go | 5 --- kentikapi/internal/resources/alerting_test.go | 6 ---- .../resources/custom_applications_test.go | 8 ----- .../resources/custom_dimensions_test.go | 19 ----------- .../internal/resources/device_labels_test.go | 10 ------ kentikapi/internal/resources/devices_test.go | 33 ------------------- .../resources/my_kentik_portal_test.go | 8 ----- kentikapi/internal/resources/plans_test.go | 2 -- kentikapi/internal/resources/query_test.go | 8 ----- .../internal/resources/saved_filters_test.go | 10 ------ kentikapi/internal/resources/sites_test.go | 10 ------ kentikapi/internal/utils/convert_test.go | 10 ------ kentikapi/internal/validation/validate.go | 2 +- kentikapi/tags_integration_test.go | 25 -------------- kentikapi/users_integration_test.go | 25 -------------- 26 files changed, 45 insertions(+), 271 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 0fac662e..1be17acc 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -16,7 +16,6 @@ issues: - should not use underscores in package names # EXC0002 golint: Annoying issue about not having a comment. The rare codebase has such comments - (comment on exported (method|function|type|const)|should have( a package)? comment|comment should be of the form) - - (struct (of|with)|could be) exclude-use-default: false exclude-rules: # exclude linters impossible to exclude via //nolint - path: ^kentikapi/models/enum_ # these files are generated and shouldn't be edited with //nolint @@ -28,20 +27,20 @@ issues: # Disabled linters: # - cyclop - duplicates functionality of gocyclo # - exhaustivestruct - breaks "Make the zero value useful" proverb, meant to be used only for special cases -# - funlen - only test functions exceeds the line limit of 60 - too strict, these functions are easily readable +# - funlen - not needed - gocyclo ensures that functions complexity is not too high # - godox - requires all TODOs to be removed - too strict +# - golint - deprecated (since v1.41.0) due to: The repository of the linter has been archived by the owner # - gomoddirectives - does not allow "replace" directives - too strict # - goerr113 - following check is too strict: "do not define dynamic errors, use wrapped static errors instead", # the check cannot be disabled # - interfacer - deprecated (since v1.38.0) due to: The repository of the linter has been archived by the owner # - maligned - deprecated (since v1.38.0) due to: The repository of the linter has been archived by the owner # - nlreturn - leads to using too many line breaks -# - prealloc - from docs: - # XXX: we don't recommend using this linter before doing performance profiling. - # For most programs usage of prealloc will be a premature optimization. +# - paralleltest - premature optimization +# - prealloc - considered a premature optimization. # - scopelint - deprecated (since v1.39.0) due to: The repository of the linter has been deprecated by the owner # - thelper - enforcing t.Helper() everywhere is too strict -# - wrapcheck - valuable linter which I think needs higher level knowledge on the project to be fixed +# - wrapcheck - valuable linter, TODO: ignore false-positives (interfaces, internal imports) and adjust the code to comply # - wsl - leads to using too many line breaks linters: enable: @@ -70,7 +69,6 @@ linters: - gofumpt - goheader - goimports - - revive - gomnd - gomodguard - goprintffuncname @@ -88,7 +86,6 @@ linters: - nilerr - noctx - nolintlint - - paralleltest - predeclared - revive - rowserrcheck @@ -107,8 +104,6 @@ linters: - whitespace linters-settings: - dupl: - tests: false errcheck: check-type-assertions: true check-blank: true @@ -116,15 +111,14 @@ linters-settings: # Check whether fmt.Errorf uses the %w verb for formatting errors - too strict errorf: false gocyclo: - min-complexity: 11 - golint: - min-confidence: 0 - gosec: - tests: false + min-complexity: 10 govet: + disable: + # Reordering struct fields may decrease readability + - fieldalignment enable-all: true lll: - # lines longer than 127 will be reported, 120 is default + # TODO: 120 (default) should be achieved to increase comfort of window split view line-length: 127 nakedret: max-func-lines: 5 \ No newline at end of file diff --git a/apiv6/examples/cloud_export/main.go b/apiv6/examples/cloud_export/main.go index 73a6673c..66000e2c 100644 --- a/apiv6/examples/cloud_export/main.go +++ b/apiv6/examples/cloud_export/main.go @@ -40,7 +40,7 @@ func runCRUD(client *kentikapi.Client) error { createReqPayload := *cloudexport.NewV202101beta1CreateCloudExportRequest() createReqPayload.Export = export - createResp, httpResp, err := client.CloudExportAdminServiceApi. + createResp, httpResp, err := client.CloudExportAdminServiceAPI. ExportCreate(context.Background()). Body(createReqPayload). Execute() @@ -57,7 +57,7 @@ func runCRUD(client *kentikapi.Client) error { updateReqPayload := *cloudexport.NewV202101beta1UpdateCloudExportRequest() updateReqPayload.Export = created - updateResp, httpResp, err := client.CloudExportAdminServiceApi. + updateResp, httpResp, err := client.CloudExportAdminServiceAPI. ExportUpdate(context.Background(), *created.Id). Body(updateReqPayload). Execute() @@ -68,7 +68,7 @@ func runCRUD(client *kentikapi.Client) error { fmt.Println() fmt.Println("### GET") - getResp, httpResp, err := client.CloudExportAdminServiceApi. + getResp, httpResp, err := client.CloudExportAdminServiceAPI. ExportGet(context.Background(), *created.Id). Execute() if err != nil { @@ -78,7 +78,7 @@ func runCRUD(client *kentikapi.Client) error { fmt.Println() fmt.Println("### DELETE") - deleteResp, httpResp, err := client.CloudExportAdminServiceApi. + deleteResp, httpResp, err := client.CloudExportAdminServiceAPI. ExportDelete(context.Background(), *created.Id). Execute() if err != nil { @@ -93,7 +93,7 @@ func runCRUD(client *kentikapi.Client) error { func runGetAll(client *kentikapi.Client) error { fmt.Println("### GET ALL") - getAllResp, httpResp, err := client.CloudExportAdminServiceApi. + getAllResp, httpResp, err := client.CloudExportAdminServiceAPI. ExportList(context.Background()). Execute() if err != nil { diff --git a/apiv6/examples/demos/cloud_export_demo/main.go b/apiv6/examples/demos/cloud_export_demo/main.go index 935cbdb7..e7989801 100644 --- a/apiv6/examples/demos/cloud_export_demo/main.go +++ b/apiv6/examples/demos/cloud_export_demo/main.go @@ -43,7 +43,7 @@ func createCloudExport(client *kentikapi.Client) string { createReqPayload := *cloudexport.NewV202101beta1CreateCloudExportRequest() createReqPayload.Export = export - createResp, _, err := client.CloudExportAdminServiceApi. + createResp, _, err := client.CloudExportAdminServiceAPI. ExportCreate(context.Background()). Body(createReqPayload). Execute() @@ -56,7 +56,7 @@ func createCloudExport(client *kentikapi.Client) string { func getCloudExport(client *kentikapi.Client, id string) *cloudexport.V202101beta1CloudExport { fmt.Printf("Retrieving cloud export of ID = %s\n", id) - getResp, _, err := client.CloudExportAdminServiceApi. + getResp, _, err := client.CloudExportAdminServiceAPI. ExportGet(context.Background(), id). Execute() demos.ExitOnError(err) @@ -70,7 +70,7 @@ func updateCloudExport(client *kentikapi.Client, export *cloudexport.V202101beta updateReqPayload := *cloudexport.NewV202101beta1UpdateCloudExportRequest() updateReqPayload.Export = export - updateResp, _, err := client.CloudExportAdminServiceApi. + updateResp, _, err := client.CloudExportAdminServiceAPI. ExportUpdate(context.Background(), *export.Id). Body(updateReqPayload). Execute() @@ -81,7 +81,7 @@ func updateCloudExport(client *kentikapi.Client, export *cloudexport.V202101beta func deleteCloudExport(client *kentikapi.Client, id string) { fmt.Printf("Deleting cloud export of ID = %s\n", id) - deleteResp, _, err := client.CloudExportAdminServiceApi. + deleteResp, _, err := client.CloudExportAdminServiceAPI. ExportDelete(context.Background(), id). Execute() demos.ExitOnError(err) @@ -91,7 +91,7 @@ func deleteCloudExport(client *kentikapi.Client, id string) { } func getAllCloudExports(client *kentikapi.Client) { - getAllResp, _, err := client.CloudExportAdminServiceApi. + getAllResp, _, err := client.CloudExportAdminServiceAPI. ExportList(context.Background()). Execute() demos.ExitOnError(err) diff --git a/apiv6/examples/demos/retry_demo/main.go b/apiv6/examples/demos/retry_demo/main.go index 70892e6b..064b6183 100644 --- a/apiv6/examples/demos/retry_demo/main.go +++ b/apiv6/examples/demos/retry_demo/main.go @@ -53,7 +53,7 @@ func showRetryingOnMultipleCodes() error { }) demos.Step("List synthetic agents") - result, _, err := c.SyntheticsAdminServiceApi. + result, _, err := c.SyntheticsAdminServiceAPI. AgentsList(context.Background()). Execute() diff --git a/apiv6/examples/synthetics/main.go b/apiv6/examples/synthetics/main.go index 39af9857..52f587fe 100644 --- a/apiv6/examples/synthetics/main.go +++ b/apiv6/examples/synthetics/main.go @@ -64,7 +64,7 @@ func runCRUDTest(client *kentikapi.Client) error { createReqPayload := *synthetics.NewV202101beta1CreateTestRequest() createReqPayload.SetTest(*test) - createResp, httpResp, err := client.SyntheticsAdminServiceApi. + createResp, httpResp, err := client.SyntheticsAdminServiceAPI. TestCreate(context.Background()). Body(createReqPayload). Execute() @@ -82,7 +82,7 @@ func runCRUDTest(client *kentikapi.Client) error { setStatusReqPayload.Status = &status setStatusReqPayload.Id = &testID - statusResp, httpResp, err := client.SyntheticsAdminServiceApi. + statusResp, httpResp, err := client.SyntheticsAdminServiceAPI. TestStatusUpdate(context.Background(), testID). Body(setStatusReqPayload). Execute() @@ -94,7 +94,7 @@ func runCRUDTest(client *kentikapi.Client) error { fmt.Println() fmt.Println("### GET TEST") - getReq := client.SyntheticsAdminServiceApi.TestGet(context.Background(), testID) + getReq := client.SyntheticsAdminServiceAPI.TestGet(context.Background(), testID) getResp, httpResp, err := getReq.Execute() if err != nil { return fmt.Errorf("%v %v", err, httpResp) @@ -112,7 +112,7 @@ func runCRUDTest(client *kentikapi.Client) error { patchReqPayload.SetTest(*test) patchReqPayload.SetMask("test.name") - patchResp, httpResp, err := client.SyntheticsAdminServiceApi. + patchResp, httpResp, err := client.SyntheticsAdminServiceAPI. TestPatch(context.Background(), *test.Id). Body(patchReqPayload). Execute() @@ -123,7 +123,7 @@ func runCRUDTest(client *kentikapi.Client) error { fmt.Println() fmt.Println("### DELETE TEST") - deleteReq := client.SyntheticsAdminServiceApi.TestDelete(context.Background(), testID) + deleteReq := client.SyntheticsAdminServiceAPI.TestDelete(context.Background(), testID) deleteResp, httpResp, err := deleteReq.Execute() if err != nil { return fmt.Errorf("%v %v", err, httpResp) @@ -138,7 +138,7 @@ func runCRUDTest(client *kentikapi.Client) error { func runListTests(client *kentikapi.Client) error { fmt.Println("### LIST TESTS") - getAllReq := client.SyntheticsAdminServiceApi.TestsList(context.Background()) + getAllReq := client.SyntheticsAdminServiceAPI.TestsList(context.Background()) getAllResp, httpResp, err := getAllReq.Execute() if err != nil { return fmt.Errorf("%v %v", err, httpResp) @@ -167,7 +167,7 @@ func runGetHealthForTests(client *kentikapi.Client, testIDs []string) error { healthPayload.SetEndTime(time.Now()) healthPayload.SetIds(testIDs) - getHealthResp, httpResp, err := client.SyntheticsDataServiceApi. + getHealthResp, httpResp, err := client.SyntheticsDataServiceAPI. GetHealthForTests(context.Background()). Body(healthPayload). Execute() @@ -195,7 +195,7 @@ func runGetTraceForTest(client *kentikapi.Client, testID string) error { tracePayload.SetStartTime(time.Now().Add(-time.Hour)) tracePayload.SetEndTime(time.Now()) - getTraceResp, httpResp, err := client.SyntheticsDataServiceApi. + getTraceResp, httpResp, err := client.SyntheticsDataServiceAPI. GetTraceForTest(context.Background(), testID). Body(tracePayload). Execute() @@ -230,7 +230,7 @@ func runCRUDAgent(client *kentikapi.Client) error { agentID := "1717" fmt.Println("### GET AGENT") - getReq := client.SyntheticsAdminServiceApi.AgentGet(context.Background(), agentID) + getReq := client.SyntheticsAdminServiceAPI.AgentGet(context.Background(), agentID) getResp, httpResp, err := getReq.Execute() if err != nil { return fmt.Errorf("%v %v", err, httpResp) @@ -249,7 +249,7 @@ func runCRUDAgent(client *kentikapi.Client) error { patchReqPayload.SetAgent(agent) patchReqPayload.SetMask("agent.family") - patchResp, httpResp, err := client.SyntheticsAdminServiceApi. + patchResp, httpResp, err := client.SyntheticsAdminServiceAPI. AgentPatch(context.Background(), agentID). Body(patchReqPayload). Execute() @@ -261,7 +261,7 @@ func runCRUDAgent(client *kentikapi.Client) error { // NOTE: as we can't create agents through the API - let's not delete them // fmt.Println("### DELETE AGENT") - // deleteReq := client.SyntheticsAdminServiceApi.AgentDelete(context.Background(), agentID) + // deleteReq := client.SyntheticsAdminServiceAPI.AgentDelete(context.Background(), agentID) // deleteResp, httpResp, err := deleteReq.Execute() // if err != nil { // return fmt.Errorf("%v %v", err, httpResp) @@ -276,7 +276,7 @@ func runCRUDAgent(client *kentikapi.Client) error { func runListAgents(client *kentikapi.Client) error { fmt.Println("### LIST AGENTS") - getAllReq := client.SyntheticsAdminServiceApi.AgentsList(context.Background()) + getAllReq := client.SyntheticsAdminServiceAPI.AgentsList(context.Background()) getAllResp, httpResp, err := getAllReq.Execute() if err != nil { return fmt.Errorf("%v %v", err, httpResp) diff --git a/apiv6/examples/synthetics/mesh_test/main.go b/apiv6/examples/synthetics/mesh_test/main.go index f34fffb8..774d047d 100644 --- a/apiv6/examples/synthetics/mesh_test/main.go +++ b/apiv6/examples/synthetics/mesh_test/main.go @@ -37,7 +37,7 @@ func getMeshTestResults(testID string) *[]synthetics.V202101beta1MeshResponse { healthPayload.SetIds([]string{testID}) healthPayload.SetAugment(true) // if not set, returned Mesh pointer will be empty - getHealthResp, httpResp, err := client.SyntheticsDataServiceApi. + getHealthResp, httpResp, err := client.SyntheticsDataServiceAPI. GetHealthForTests(context.Background()). Body(healthPayload). Execute() diff --git a/apiv6/kentikapi/client.go b/apiv6/kentikapi/client.go index 95e16411..bcd13f0a 100644 --- a/apiv6/kentikapi/client.go +++ b/apiv6/kentikapi/client.go @@ -1,4 +1,3 @@ -//nolint:revive,stylecheck // Changing Api to API forces changes in generated files package kentikapi import ( @@ -18,11 +17,11 @@ const ( // Client is the root object for manipulating all the Kentik API resources. type Client struct { // cloudexport - CloudExportAdminServiceApi *cloudexport.CloudExportAdminServiceApiService + CloudExportAdminServiceAPI *cloudexport.CloudExportAdminServiceApiService // synthetics - SyntheticsAdminServiceApi *synthetics.SyntheticsAdminServiceApiService - SyntheticsDataServiceApi *synthetics.SyntheticsDataServiceApiService + SyntheticsAdminServiceAPI *synthetics.SyntheticsAdminServiceApiService + SyntheticsDataServiceAPI *synthetics.SyntheticsDataServiceApiService } // Config holds configuration of the Client. @@ -54,9 +53,9 @@ func NewClient(c Config) *Client { syntheticsClient := synthetics.NewAPIClient(makeSyntheticsConfig(c)) return &Client{ - CloudExportAdminServiceApi: cloudexportClient.CloudExportAdminServiceApi, - SyntheticsAdminServiceApi: syntheticsClient.SyntheticsAdminServiceApi, - SyntheticsDataServiceApi: syntheticsClient.SyntheticsDataServiceApi, + CloudExportAdminServiceAPI: cloudexportClient.CloudExportAdminServiceApi, + SyntheticsAdminServiceAPI: syntheticsClient.SyntheticsAdminServiceApi, + SyntheticsDataServiceAPI: syntheticsClient.SyntheticsDataServiceApi, } } diff --git a/apiv6/kentikapi/client_integration_test.go b/apiv6/kentikapi/client_integration_test.go index 4c0029ba..8099460e 100644 --- a/apiv6/kentikapi/client_integration_test.go +++ b/apiv6/kentikapi/client_integration_test.go @@ -25,10 +25,7 @@ const ( testAgentID = "968" ) -//nolint:errcheck // Conflict with defer Close() (additional info: https://github.com/kisielk/errcheck/issues/55) func TestClient_PatchAgent(t *testing.T) { - t.Parallel() - tests := []struct { name string retryMax *int @@ -164,10 +161,7 @@ func TestClient_PatchAgent(t *testing.T) { }, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { - t.Parallel() - // arrange h := newSpyHTTPHandler(t, tt.responses) s := httptest.NewServer(h) @@ -188,10 +182,11 @@ func TestClient_PatchAgent(t *testing.T) { }) // act - result, httpResp, err := c.SyntheticsAdminServiceApi. + result, httpResp, err := c.SyntheticsAdminServiceAPI. AgentPatch(context.Background(), testAgentID). Body(tt.request). Execute() + //nolint:errcheck // Additional info: https://github.com/kisielk/errcheck/issues/55 defer httpResp.Body.Close() // assert diff --git a/apiv6/kentikapi/httputil/httputil_test.go b/apiv6/kentikapi/httputil/httputil_test.go index 7e434207..1cc1098c 100644 --- a/apiv6/kentikapi/httputil/httputil_test.go +++ b/apiv6/kentikapi/httputil/httputil_test.go @@ -22,11 +22,7 @@ import ( // 4. retryingClient.retryableRoundTripper.retryableClient.httpClient.Do() // 5. retryingClient.retryableRoundTripper.retryableClient.httpClient.httpTransport.RoundTrip() -//nolint:errcheck // https://github.com/kisielk/errcheck/issues/55 -// Closing a response you only read from cannot yield a meaningful error. func TestRetryingClient_Do_ReturnsHTTPTransportError(t *testing.T) { - t.Parallel() - // arrange c := httputil.NewRetryingClient(httputil.ClientConfig{}) @@ -34,11 +30,8 @@ func TestRetryingClient_Do_ReturnsHTTPTransportError(t *testing.T) { require.NoError(t, err) // act + //nolint:bodyclose resp, err := c.Do(req.WithContext(context.Background())) - if err != nil { - return - } - defer resp.Body.Close() // assert t.Logf("Got response: %v, err: %v", resp, err) @@ -48,11 +41,7 @@ func TestRetryingClient_Do_ReturnsHTTPTransportError(t *testing.T) { assert.Equal(t, "no such host", dnsErr.Err) } -//nolint:errcheck // https://github.com/kisielk/errcheck/issues/55 -// Closing a response you only read from cannot yield a meaningful error. func TestRetryingClientWithSpyHTTPTransport_Do(t *testing.T) { - t.Parallel() - const retryMax = 5 tests := []struct { @@ -85,10 +74,7 @@ func TestRetryingClientWithSpyHTTPTransport_Do(t *testing.T) { }, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { - t.Parallel() - // arrange st := spyTransport{transportError: tt.transportError} c := httputil.NewRetryingClient(httputil.ClientConfig{ @@ -106,11 +92,8 @@ func TestRetryingClientWithSpyHTTPTransport_Do(t *testing.T) { require.NoError(t, err) // act + //nolint:bodyclose resp, err := c.Do(req.WithContext(context.Background())) - if err != nil { - return - } - defer resp.Body.Close() // assert t.Logf("Got response: %v, err: %v", resp, err) diff --git a/examples/custom_applications_example_test.go b/examples/custom_applications_example_test.go index 3ee20525..6941d013 100644 --- a/examples/custom_applications_example_test.go +++ b/examples/custom_applications_example_test.go @@ -12,8 +12,6 @@ import ( ) func TestCustomApplicationsAPIExample(t *testing.T) { - t.Parallel() - assert := assert.New(t) assert.NoError(runCRUDCustomApplications()) assert.NoError(runGetAllCustomApplications()) diff --git a/kentikapi/internal/api_payloads/query_test.go b/kentikapi/internal/api_payloads/query_test.go index 631daeab..6532ec65 100644 --- a/kentikapi/internal/api_payloads/query_test.go +++ b/kentikapi/internal/api_payloads/query_test.go @@ -12,8 +12,6 @@ import ( ) func TestQueryChartResponsePNGToQueryChartResult(t *testing.T) { - t.Parallel() - // arrange data := "ImagePNGEncodedBase64str" decodedData := base64Decode(t, data) @@ -29,8 +27,6 @@ func TestQueryChartResponsePNGToQueryChartResult(t *testing.T) { } func TestQueryChartResponseJPEGToQueryChartResult(t *testing.T) { - t.Parallel() - // arrange data := "ImageJPGEncodedBase64str" decodedData := base64Decode(t, data) @@ -46,8 +42,6 @@ func TestQueryChartResponseJPEGToQueryChartResult(t *testing.T) { } func TestQueryChartResponseSVGToQueryChartResult(t *testing.T) { - t.Parallel() - // arrange data := "ImageSVGEncodedBase64str" decodedData := base64Decode(t, data) @@ -63,8 +57,6 @@ func TestQueryChartResponseSVGToQueryChartResult(t *testing.T) { } func TestQueryChartResponsePDFToQueryChartResult(t *testing.T) { - t.Parallel() - // arrange data := "ApplicationPDFEncodedBase64str==" decodedData := base64Decode(t, data) @@ -80,8 +72,6 @@ func TestQueryChartResponsePDFToQueryChartResult(t *testing.T) { } func TestUnknownFormatResultsInError(t *testing.T) { - t.Parallel() - // arrange data := "ImageBMPEncodedBase64str==" response := api_payloads.QueryChartResponse{DataURI: "data:image/bmp;base64," + data} @@ -94,8 +84,6 @@ func TestUnknownFormatResultsInError(t *testing.T) { } func TestUnknownEncodingResultsInError(t *testing.T) { - t.Parallel() - // arrange data := "ImagePNGEncodedBase32str==" response := api_payloads.QueryChartResponse{DataURI: "data:image/png;base32," + data} @@ -108,8 +96,6 @@ func TestUnknownEncodingResultsInError(t *testing.T) { } func TestFormatQueryTimeNonNil(t *testing.T) { - t.Parallel() - // arrange datetime := time.Date(2001, 3, 9, 6, 45, 53, 111, time.UTC) @@ -122,8 +108,6 @@ func TestFormatQueryTimeNonNil(t *testing.T) { } func TestFormatQueryTimeNil(t *testing.T) { - t.Parallel() - // arrange var datetime *time.Time diff --git a/kentikapi/internal/api_payloads/types_test.go b/kentikapi/internal/api_payloads/types_test.go index 6e4dc403..61cca0e8 100644 --- a/kentikapi/internal/api_payloads/types_test.go +++ b/kentikapi/internal/api_payloads/types_test.go @@ -9,8 +9,6 @@ import ( ) func TestBoolAsString_UnmarshalJSON(t *testing.T) { - t.Parallel() - tests := []struct { input string expectedResult api_payloads.BoolAsStringOrInt @@ -52,10 +50,7 @@ func TestBoolAsString_UnmarshalJSON(t *testing.T) { }, } for _, tt := range tests { - tt := tt t.Run(tt.input, func(t *testing.T) { - t.Parallel() - var result api_payloads.BoolAsStringOrInt err := json.Unmarshal([]byte(tt.input), &result) diff --git a/kentikapi/internal/resources/alerting_test.go b/kentikapi/internal/resources/alerting_test.go index e9993d66..7e698aeb 100644 --- a/kentikapi/internal/resources/alerting_test.go +++ b/kentikapi/internal/resources/alerting_test.go @@ -18,8 +18,6 @@ var ( ) func TestCrerateManualMitigation(t *testing.T) { - t.Parallel() - createResponsePayload := ` { "response": { @@ -44,8 +42,6 @@ func TestCrerateManualMitigation(t *testing.T) { } func TestGetActiveAlerts(t *testing.T) { - t.Parallel() - getResponsePayload := ` [ { @@ -143,8 +139,6 @@ func TestGetActiveAlerts(t *testing.T) { } func TestGetAlertsHistory(t *testing.T) { - t.Parallel() - getResponsePayload := ` [ { diff --git a/kentikapi/internal/resources/custom_applications_test.go b/kentikapi/internal/resources/custom_applications_test.go index 0bc2a3fc..9768c22d 100644 --- a/kentikapi/internal/resources/custom_applications_test.go +++ b/kentikapi/internal/resources/custom_applications_test.go @@ -15,8 +15,6 @@ import ( ) func TestGetAll(t *testing.T) { - t.Parallel() - getResponsePayload := ` [ { @@ -78,8 +76,6 @@ func TestGetAll(t *testing.T) { } func TestCreateCustomApplication(t *testing.T) { - t.Parallel() - createResponsePayload := ` { "name": "apitest-customapp-1", @@ -134,8 +130,6 @@ func TestCreateCustomApplication(t *testing.T) { } func TestUpdateCustomApplication(t *testing.T) { - t.Parallel() - updateResponsePayload := ` { "id": 207, @@ -194,8 +188,6 @@ func TestUpdateCustomApplication(t *testing.T) { } func TestDeleteCustomApplication(t *testing.T) { - t.Parallel() - // arrange deleteResponsePayload := "" // deleting custom application responds with empty body transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} diff --git a/kentikapi/internal/resources/custom_dimensions_test.go b/kentikapi/internal/resources/custom_dimensions_test.go index b3d52b61..50a581c9 100644 --- a/kentikapi/internal/resources/custom_dimensions_test.go +++ b/kentikapi/internal/resources/custom_dimensions_test.go @@ -17,8 +17,6 @@ import ( ) func TestCreateCustomDimension(t *testing.T) { - t.Parallel() - // arrange createResponsePayload := ` { @@ -64,8 +62,6 @@ func TestCreateCustomDimension(t *testing.T) { } func TestUpdateCustomDimension(t *testing.T) { - t.Parallel() - // arrange updateResponsePayload := ` { @@ -106,8 +102,6 @@ func TestUpdateCustomDimension(t *testing.T) { } func TestGetCustomDimension(t *testing.T) { - t.Parallel() - tests := []struct { name string transportError error @@ -317,10 +311,7 @@ func TestGetCustomDimension(t *testing.T) { }, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { - t.Parallel() - // arrange transport := &api_connection.StubTransport{ResponseBody: tt.responseBody} customDimensionsAPI := resources.NewCustomDimensionsAPI(transport) @@ -346,8 +337,6 @@ func TestGetCustomDimension(t *testing.T) { } func TestGetAllCustomDimensions(t *testing.T) { - t.Parallel() - // arrange getResponsePayload := ` { @@ -431,8 +420,6 @@ func TestGetAllCustomDimensions(t *testing.T) { } func TestDeleteCustomDimension(t *testing.T) { - t.Parallel() - // arrange deleteResponsePayload := "" // deleting device responds with empty body transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} @@ -452,8 +439,6 @@ func TestDeleteCustomDimension(t *testing.T) { } func TestCreatePopulator(t *testing.T) { - t.Parallel() - // arrange createResponsePayload := ` { @@ -580,8 +565,6 @@ func TestCreatePopulator(t *testing.T) { } func TestUpdatePopulator(t *testing.T) { - t.Parallel() - // arrange updateResponsePayload := ` { @@ -660,8 +643,6 @@ func TestUpdatePopulator(t *testing.T) { } func TestDeletePopulator(t *testing.T) { - t.Parallel() - // arrange deleteResponsePayload := "" // deleting device responds with empty body transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} diff --git a/kentikapi/internal/resources/device_labels_test.go b/kentikapi/internal/resources/device_labels_test.go index fb50278b..4378c0fd 100644 --- a/kentikapi/internal/resources/device_labels_test.go +++ b/kentikapi/internal/resources/device_labels_test.go @@ -15,8 +15,6 @@ import ( ) func TestCreateDeviceLabel(t *testing.T) { - t.Parallel() - // arrange createResponsePayload := ` { @@ -59,8 +57,6 @@ func TestCreateDeviceLabel(t *testing.T) { } func TestUpdateDeviceLabel(t *testing.T) { - t.Parallel() - // arrange updateResponsePayload := ` { @@ -103,8 +99,6 @@ func TestUpdateDeviceLabel(t *testing.T) { } func TestGetLabel(t *testing.T) { - t.Parallel() - // arrange getResponsePayload := ` { @@ -155,8 +149,6 @@ func TestGetLabel(t *testing.T) { } func TestGetAllLabels(t *testing.T) { - t.Parallel() - // arrange getResponsePayload := ` [ @@ -236,8 +228,6 @@ func TestGetAllLabels(t *testing.T) { } func TestDeleteDeviceLabel(t *testing.T) { - t.Parallel() - // arrange deleteResponsePayload := ` { diff --git a/kentikapi/internal/resources/devices_test.go b/kentikapi/internal/resources/devices_test.go index 65470b7c..8f7ce321 100644 --- a/kentikapi/internal/resources/devices_test.go +++ b/kentikapi/internal/resources/devices_test.go @@ -18,8 +18,6 @@ import ( ) func TestCreateDeviceRouter(t *testing.T) { - t.Parallel() - // arrange createResponsePayload := ` { @@ -212,8 +210,6 @@ func TestCreateDeviceRouter(t *testing.T) { } func TestCreateDeviceDNS(t *testing.T) { - t.Parallel() - // arrange createResponsePayload := ` { @@ -365,8 +361,6 @@ func TestCreateDeviceDNS(t *testing.T) { } func TestUpdatetDeviceRouter(t *testing.T) { - t.Parallel() - // arrange updateResponsePayload := ` { @@ -562,8 +556,6 @@ func TestUpdatetDeviceRouter(t *testing.T) { } func TestGetDevice(t *testing.T) { - t.Parallel() - tests := []struct { name string transportError error @@ -1088,10 +1080,7 @@ func TestGetDevice(t *testing.T) { }, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { - t.Parallel() - // arrange transport := &api_connection.StubTransport{ResponseBody: tt.responseBody} devicesAPI := resources.NewDevicesAPI(transport) @@ -1117,8 +1106,6 @@ func TestGetDevice(t *testing.T) { } func TestGetAllDevices(t *testing.T) { - t.Parallel() - // arrange getResponsePayload := ` { @@ -1389,8 +1376,6 @@ func TestGetAllDevices(t *testing.T) { } func TestDeleteDevice(t *testing.T) { - t.Parallel() - // arrange deleteResponsePayload := "" // deleting device responds with empty body transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} @@ -1410,8 +1395,6 @@ func TestDeleteDevice(t *testing.T) { } func TestApplyLabels(t *testing.T) { - t.Parallel() - // arrange applyLabelsResponsePayload := ` { @@ -1488,8 +1471,6 @@ func TestApplyLabels(t *testing.T) { } func TestGetInterfaceMinimal(t *testing.T) { - t.Parallel() - // arrange getResponsePayload := ` { @@ -1557,8 +1538,6 @@ func TestGetInterfaceMinimal(t *testing.T) { } func TestGetInterfaceFull(t *testing.T) { - t.Parallel() - // arrange getResponsePayload := ` { @@ -1676,8 +1655,6 @@ func TestGetInterfaceFull(t *testing.T) { } func TestGetAllInterfaces(t *testing.T) { - t.Parallel() - // arrange getResponsePayload := ` [ @@ -1867,8 +1844,6 @@ func TestGetAllInterfaces(t *testing.T) { } func TestCreateInterfaceMinimal(t *testing.T) { - t.Parallel() - // arrange getResponsePayload := ` { @@ -1924,8 +1899,6 @@ func TestCreateInterfaceMinimal(t *testing.T) { } func TestCreateInterfaceFull(t *testing.T) { - t.Parallel() - // arrange getResponsePayload := ` { @@ -2026,8 +1999,6 @@ func TestCreateInterfaceFull(t *testing.T) { } func TestDeleteInterface(t *testing.T) { - t.Parallel() - // arrange deleteResponsePayload := "{}" transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} @@ -2048,8 +2019,6 @@ func TestDeleteInterface(t *testing.T) { } func TestUpdateInterfaceMinimal(t *testing.T) { - t.Parallel() - updateResponsePayload := ` { "id": "43", @@ -2127,8 +2096,6 @@ func TestUpdateInterfaceMinimal(t *testing.T) { } func TestUpdateInterfaceFull(t *testing.T) { - t.Parallel() - updateResponsePayload := ` { "id": "43", diff --git a/kentikapi/internal/resources/my_kentik_portal_test.go b/kentikapi/internal/resources/my_kentik_portal_test.go index 6dd54f7f..d21fc195 100644 --- a/kentikapi/internal/resources/my_kentik_portal_test.go +++ b/kentikapi/internal/resources/my_kentik_portal_test.go @@ -14,8 +14,6 @@ import ( ) func TestTenantsList(t *testing.T) { - t.Parallel() - // arrange getAllResponse := ` [ @@ -102,8 +100,6 @@ func TestTenantsList(t *testing.T) { } func TestGetTenantInfo(t *testing.T) { - t.Parallel() - getTenantInfoResponse := ` { "id": 577, @@ -169,8 +165,6 @@ func TestGetTenantInfo(t *testing.T) { } func TestTenantUserCreate(t *testing.T) { - t.Parallel() - createTenantUserResponse := ` { "id": "158564", @@ -206,8 +200,6 @@ func TestTenantUserCreate(t *testing.T) { } func TestTenantUserDelete(t *testing.T) { - t.Parallel() - // arrange deleteResponsePayload := "" transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} diff --git a/kentikapi/internal/resources/plans_test.go b/kentikapi/internal/resources/plans_test.go index 07dbd657..bc4f4c6f 100644 --- a/kentikapi/internal/resources/plans_test.go +++ b/kentikapi/internal/resources/plans_test.go @@ -12,8 +12,6 @@ import ( ) func TestGetAllPlans(t *testing.T) { - t.Parallel() - // arrange getResponsePayload := ` { diff --git a/kentikapi/internal/resources/query_test.go b/kentikapi/internal/resources/query_test.go index b525bef3..b57ea376 100644 --- a/kentikapi/internal/resources/query_test.go +++ b/kentikapi/internal/resources/query_test.go @@ -15,8 +15,6 @@ import ( ) func TestQuerySQL(t *testing.T) { - t.Parallel() - // arrange querySQL := ` SELECT i_start_time, @@ -86,8 +84,6 @@ func TestQuerySQL(t *testing.T) { } func TestQueryData(t *testing.T) { - t.Parallel() - // arrange queryResponsePayload := ` { @@ -217,8 +213,6 @@ func TestQueryData(t *testing.T) { } func TestQueryChart(t *testing.T) { - t.Parallel() - // arrange data := "ImageDataEncodedBase64==" queryResponsePayload := `{"dataUri": "data:image/png;base64,ImageDataEncodedBase64=="}` @@ -361,8 +355,6 @@ func TestQueryChart(t *testing.T) { } func TestQueryURL(t *testing.T) { - t.Parallel() - // arrange unquotedResponse := "https://portal.kentik.com/portal/#Charts/shortUrl/e0d24b3cc8dfe41f9093668e531cbe96" queryResponsePayload := `"` + unquotedResponse + `"` // actual response is url in quotation marks diff --git a/kentikapi/internal/resources/saved_filters_test.go b/kentikapi/internal/resources/saved_filters_test.go index e21f5ba1..fb600146 100644 --- a/kentikapi/internal/resources/saved_filters_test.go +++ b/kentikapi/internal/resources/saved_filters_test.go @@ -12,8 +12,6 @@ import ( ) func TestSavedFiltersList(t *testing.T) { - t.Parallel() - getAllresponsePayload := ` [ { @@ -138,8 +136,6 @@ func TestSavedFiltersList(t *testing.T) { } func TestGetSavedFilterInfo(t *testing.T) { - t.Parallel() - getResponsePayload := ` { "id": 8275, @@ -204,8 +200,6 @@ func TestGetSavedFilterInfo(t *testing.T) { } func TestCreateSavedFilter(t *testing.T) { - t.Parallel() - postResponsePayload := ` { "filter_name":"test_filter1", @@ -294,8 +288,6 @@ func TestCreateSavedFilter(t *testing.T) { } func TestUpdateSavedFilter(t *testing.T) { - t.Parallel() - updateResponsePayload := ` { "id":8153, @@ -359,8 +351,6 @@ func TestUpdateSavedFilter(t *testing.T) { } func TestDeleteSavedFilter(t *testing.T) { - t.Parallel() - deleteResponsePayload := "" transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} diff --git a/kentikapi/internal/resources/sites_test.go b/kentikapi/internal/resources/sites_test.go index ea54eb5a..a4797b24 100644 --- a/kentikapi/internal/resources/sites_test.go +++ b/kentikapi/internal/resources/sites_test.go @@ -13,8 +13,6 @@ import ( ) func TestGetSite(t *testing.T) { - t.Parallel() - // arrange getResponsePayload := ` { @@ -49,8 +47,6 @@ func TestGetSite(t *testing.T) { } func TestGetAllSites(t *testing.T) { - t.Parallel() - // arrange getResponsePayload := ` { @@ -117,8 +113,6 @@ func TestGetAllSites(t *testing.T) { } func TestCreateSite(t *testing.T) { - t.Parallel() - // arrange createResponsePayload := ` { @@ -159,8 +153,6 @@ func TestCreateSite(t *testing.T) { } func TestUpdateSite(t *testing.T) { - t.Parallel() - // arrange updateResponsePayload := ` { @@ -201,8 +193,6 @@ func TestUpdateSite(t *testing.T) { } func TestDeleteSite(t *testing.T) { - t.Parallel() - // arrange deleteResponsePayload := "" // deleting site responds with empty body transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} diff --git a/kentikapi/internal/utils/convert_test.go b/kentikapi/internal/utils/convert_test.go index 67c5eeb2..3c01706d 100644 --- a/kentikapi/internal/utils/convert_test.go +++ b/kentikapi/internal/utils/convert_test.go @@ -9,8 +9,6 @@ import ( ) func TestConvertOrNoneReturnsValue(t *testing.T) { - t.Parallel() - // given input := new(string) *input = "42" @@ -27,8 +25,6 @@ func TestConvertOrNoneReturnsValue(t *testing.T) { } func TestConvertOrNoneReturnsNil(t *testing.T) { - t.Parallel() - // given var input *string var output *int @@ -43,8 +39,6 @@ func TestConvertOrNoneReturnsNil(t *testing.T) { } func TestConvertOrNoneReturnsError(t *testing.T) { - t.Parallel() - // given input := new(string) *input = "0xFF" @@ -59,8 +53,6 @@ func TestConvertOrNoneReturnsError(t *testing.T) { } func TestConvertListSuccess(t *testing.T) { - t.Parallel() - // given input := [...]string{"-13", "22", "742"} var output []int @@ -77,8 +69,6 @@ func TestConvertListSuccess(t *testing.T) { } func TestConvertListError(t *testing.T) { - t.Parallel() - // given input := []string{"42", "0xFF"} var output []int diff --git a/kentikapi/internal/validation/validate.go b/kentikapi/internal/validation/validate.go index de2a64fd..0f02da64 100644 --- a/kentikapi/internal/validation/validate.go +++ b/kentikapi/internal/validation/validate.go @@ -44,7 +44,7 @@ func getTypeName(i interface{}) string { return tResource.Name() } -//nolint:exhaustive +//nolint:exhaustive,gocyclo func validate(method string, direction string, path string, v reflect.Value) []string { missing := make([]string, 0) diff --git a/kentikapi/tags_integration_test.go b/kentikapi/tags_integration_test.go index 149b6066..03c9f759 100644 --- a/kentikapi/tags_integration_test.go +++ b/kentikapi/tags_integration_test.go @@ -19,8 +19,6 @@ const ( ) func TestClient_GetAllTags(t *testing.T) { - t.Parallel() - tests := []struct { name string responseCode int @@ -85,10 +83,7 @@ func TestClient_GetAllTags(t *testing.T) { }, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { - t.Parallel() - // arrange h := testutil.NewSpyHTTPHandler(t, tt.responseCode, []byte(tt.responseBody)) s := httptest.NewServer(h) @@ -123,8 +118,6 @@ func TestClient_GetAllTags(t *testing.T) { } func TestClient_GetTag(t *testing.T) { - t.Parallel() - tests := []struct { name string responseCode int @@ -157,10 +150,7 @@ func TestClient_GetTag(t *testing.T) { }, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { - t.Parallel() - // arrange h := testutil.NewSpyHTTPHandler(t, tt.responseCode, []byte(tt.responseBody)) s := httptest.NewServer(h) @@ -195,8 +185,6 @@ func TestClient_GetTag(t *testing.T) { } func TestClient_CreateTag(t *testing.T) { - t.Parallel() - tests := []struct { name string tag models.Tag @@ -339,10 +327,7 @@ func TestClient_CreateTag(t *testing.T) { }, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { - t.Parallel() - // arrange h := testutil.NewSpyHTTPHandler(t, tt.responseCode, []byte(tt.responseBody)) s := httptest.NewServer(h) @@ -378,8 +363,6 @@ func TestClient_CreateTag(t *testing.T) { } func TestClient_UpdateTag(t *testing.T) { - t.Parallel() - tests := []struct { name string tag models.Tag @@ -510,10 +493,7 @@ func TestClient_UpdateTag(t *testing.T) { }, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { - t.Parallel() - // arrange h := testutil.NewSpyHTTPHandler(t, tt.responseCode, []byte(tt.responseBody)) s := httptest.NewServer(h) @@ -550,8 +530,6 @@ func TestClient_UpdateTag(t *testing.T) { } func TestClient_DeleteTag(t *testing.T) { - t.Parallel() - tests := []struct { name string responseCode int @@ -575,10 +553,7 @@ func TestClient_DeleteTag(t *testing.T) { }, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { - t.Parallel() - // arrange h := testutil.NewSpyHTTPHandler(t, tt.responseCode, []byte(tt.responseBody)) s := httptest.NewServer(h) diff --git a/kentikapi/users_integration_test.go b/kentikapi/users_integration_test.go index 98a3394f..402cdf26 100644 --- a/kentikapi/users_integration_test.go +++ b/kentikapi/users_integration_test.go @@ -28,8 +28,6 @@ const ( type object = map[string]interface{} func TestClient_GetAllUsers(t *testing.T) { - t.Parallel() - tests := []struct { name string responseCode int @@ -162,10 +160,7 @@ func TestClient_GetAllUsers(t *testing.T) { }, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { - t.Parallel() - // arrange h := testutil.NewSpyHTTPHandler(t, tt.responseCode, []byte(tt.responseBody)) s := httptest.NewServer(h) @@ -200,8 +195,6 @@ func TestClient_GetAllUsers(t *testing.T) { } func TestClient_GetUser(t *testing.T) { - t.Parallel() - tests := []struct { name string responses []testutil.HTTPResponse @@ -316,10 +309,7 @@ func TestClient_GetUser(t *testing.T) { }, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { - t.Parallel() - // arrange h := testutil.NewMultipleResponseSpyHTTPHandler(t, tt.responses) s := httptest.NewServer(h) @@ -360,8 +350,6 @@ func TestClient_GetUser(t *testing.T) { } func TestClient_CreateUser(t *testing.T) { - t.Parallel() - tests := []struct { name string retryMax *int @@ -541,10 +529,7 @@ func TestClient_CreateUser(t *testing.T) { }, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { - t.Parallel() - // arrange h := testutil.NewMultipleResponseSpyHTTPHandler(t, tt.responses) s := httptest.NewServer(h) @@ -587,8 +572,6 @@ func TestClient_CreateUser(t *testing.T) { } func TestClient_UpdateUser(t *testing.T) { - t.Parallel() - tests := []struct { name string user models.User @@ -686,10 +669,7 @@ func TestClient_UpdateUser(t *testing.T) { }, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { - t.Parallel() - // arrange h := testutil.NewSpyHTTPHandler(t, tt.responseCode, []byte(tt.responseBody)) s := httptest.NewServer(h) @@ -726,8 +706,6 @@ func TestClient_UpdateUser(t *testing.T) { } func TestClient_DeleteUser(t *testing.T) { - t.Parallel() - tests := []struct { name string responseCode int @@ -751,10 +729,7 @@ func TestClient_DeleteUser(t *testing.T) { }, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { - t.Parallel() - // arrange h := testutil.NewSpyHTTPHandler(t, tt.responseCode, []byte(tt.responseBody)) s := httptest.NewServer(h) From 6f8129d4106cf250058c83afd6fdd215d9948d9e Mon Sep 17 00:00:00 2001 From: maciej palczynski Date: Thu, 9 Sep 2021 14:52:49 +0200 Subject: [PATCH 4/6] Implemented second batch of suggestions from review --- .golangci.yml | 8 +++++++ .../synthetics/mesh_test/metrics_matrix.go | 2 +- apiv6/kentikapi/client.go | 2 +- .../cloudexport/go/routers.go | 2 +- .../synthetics/go/routers.go | 2 +- kentikapi/internal/api_payloads/interface.go | 22 +++++++++---------- kentikapi/internal/api_payloads/query.go | 8 +++---- .../internal/api_payloads/saved_filter.go | 5 ++--- kentikapi/internal/resources/alerting.go | 4 ++-- .../internal/resources/custom_applications.go | 16 +++++++++----- .../internal/resources/custom_dimensions.go | 6 +++-- kentikapi/internal/resources/devices_test.go | 2 +- .../internal/resources/my_kentik_portal.go | 4 ++-- kentikapi/internal/resources/tags.go | 1 - kentikapi/internal/resources/users.go | 1 - kentikapi/models/device.go | 4 ++-- kentikapi/tags_integration_test.go | 5 ++++- kentikapi/users_integration_test.go | 3 ++- 18 files changed, 56 insertions(+), 41 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 1be17acc..8e7bcd31 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -23,6 +23,14 @@ issues: - gochecknoglobals - lll - gomnd + # tags.go and users.go are called by dupl in entirety. Nolints on package level are not recommended, + # so this is a workaround. + - path: kentikapi/internal/resources/tags.go + linters: + - dupl + - path: kentikapi/internal/resources/users.go + linters: + - dupl # Disabled linters: # - cyclop - duplicates functionality of gocyclo diff --git a/apiv6/examples/synthetics/mesh_test/metrics_matrix.go b/apiv6/examples/synthetics/mesh_test/metrics_matrix.go index c83d1686..c5af160d 100644 --- a/apiv6/examples/synthetics/mesh_test/metrics_matrix.go +++ b/apiv6/examples/synthetics/mesh_test/metrics_matrix.go @@ -4,7 +4,7 @@ import ( "github.com/kentik/community_sdk_golang/apiv6/kentikapi/synthetics" ) -// metricsMatrix holds "fromAgent" -> "toAgent" api_connection metrics +// metricsMatrix holds "fromAgent" -> "toAgent" connection metrics type metricsMatrix struct { agents []string cells map[string]map[string]*synthetics.V202101beta1MeshMetrics diff --git a/apiv6/kentikapi/client.go b/apiv6/kentikapi/client.go index bcd13f0a..b67b0ef7 100644 --- a/apiv6/kentikapi/client.go +++ b/apiv6/kentikapi/client.go @@ -33,7 +33,7 @@ type Config struct { AuthEmail string AuthToken string RetryCfg RetryConfig - // LogPayloads enables logging of request and response api_payloads. + // LogPayloads enables logging of request and response payloads. LogPayloads bool } diff --git a/apiv6/localhost_apiserver/cloudexport/go/routers.go b/apiv6/localhost_apiserver/cloudexport/go/routers.go index 5e34a918..b6678fc9 100644 --- a/apiv6/localhost_apiserver/cloudexport/go/routers.go +++ b/apiv6/localhost_apiserver/cloudexport/go/routers.go @@ -30,7 +30,7 @@ type Route struct { HandlerFunc http.HandlerFunc } -// Routes are a collection of defined api api_endpoints +// Routes are a collection of defined api endpoints type Routes []Route // Router defines the required methods for retrieving api routes diff --git a/apiv6/localhost_apiserver/synthetics/go/routers.go b/apiv6/localhost_apiserver/synthetics/go/routers.go index 0b948aee..09b7ec13 100644 --- a/apiv6/localhost_apiserver/synthetics/go/routers.go +++ b/apiv6/localhost_apiserver/synthetics/go/routers.go @@ -30,7 +30,7 @@ type Route struct { HandlerFunc http.HandlerFunc } -// Routes are a collection of defined api api_endpoints +// Routes are a collection of defined api endpoints type Routes []Route // Router defines the required methods for retrieving api routes diff --git a/kentikapi/internal/api_payloads/interface.go b/kentikapi/internal/api_payloads/interface.go index 39d40829..3e8ad3b7 100644 --- a/kentikapi/internal/api_payloads/interface.go +++ b/kentikapi/internal/api_payloads/interface.go @@ -46,17 +46,17 @@ type UpdateInterfaceResponse = CreateInterfaceResponse // InterfacePayload represents JSON Interface payload as it is transmitted to and from KentikAPI. type InterfacePayload struct { // following fields can appear in request: post/put, response: get/post/put - SNMPID *models.ID `json:"snmp_id,string,omitempty" request:"post" response:"get,post,put"` - SNMPSpeed IntAsString `json:"snmp_speed,omitempty"` // caveat, GET returns snmp_speed as string - // but POST and PUT as int - InterfaceDescription *string `json:"interface_description,omitempty" request:"post" response:"get,post,put"` - SNMPAlias *string `json:"snmp_alias,omitempty"` - InterfaceIP *string `json:"interface_ip,omitempty"` - InterfaceIPNetmask *string `json:"interface_ip_netmask,omitempty"` - VRF *vrfAttributesPayload `json:"vrf,omitempty"` // caveat, for non-set vrf GET returns vrf as null, - // but POST and PUT as empty object "{}" - VRFID *IntAsString `json:"vrf_id,omitempty"` // caveat, GET returns vrf_id as string - // but POST and PUT as int + SNMPID *models.ID `json:"snmp_id,string,omitempty" request:"post" response:"get,post,put"` + // caveat, GET returns snmp_speed as string but POST and PUT as int + SNMPSpeed IntAsString `json:"snmp_speed,omitempty"` + InterfaceDescription *string `json:"interface_description,omitempty" request:"post" response:"get,post,put"` + SNMPAlias *string `json:"snmp_alias,omitempty"` + InterfaceIP *string `json:"interface_ip,omitempty"` + InterfaceIPNetmask *string `json:"interface_ip_netmask,omitempty"` + // caveat, for non-set vrf GET returns vrf as null, but POST and PUT as empty object "{}" + VRF *vrfAttributesPayload `json:"vrf,omitempty"` + // caveat, GET returns vrf_id as string but POST and PUT as int + VRFID *IntAsString `json:"vrf_id,omitempty"` SecondaryIPs []secondaryIPPayload `json:"secondary_ips,omitempty"` // following fields can appear in request: none, response: get/post/put diff --git a/kentikapi/internal/api_payloads/query.go b/kentikapi/internal/api_payloads/query.go index 8161178b..f27067bb 100644 --- a/kentikapi/internal/api_payloads/query.go +++ b/kentikapi/internal/api_payloads/query.go @@ -167,8 +167,8 @@ type queryPayload struct { Dimension []string `json:"dimension,omitempty"` FiltersObj *filtersPayload `json:"filters_obj,omitempty"` SavedFilters []savedFilterPayload `json:"saved_filters,omitempty"` - MatrixBy []string `json:"matrixBy" request:"post"` // matrixBy is required in request even if empty. - // Otherwise Chart query hangs + // matrixBy is required in request even if empty. Otherwise Chart query hangs + MatrixBy []string `json:"matrixBy" request:"post"` CIDR *int `json:"cidr,omitempty"` CIDR6 *int `json:"cidr6,omitempty"` PPSThreshold *int `json:"pps_threshold,omitempty"` @@ -220,7 +220,7 @@ func queryToPayload(q models.Query) (queryPayload, error) { return queryPayload{ Metric: q.Metric.String(), Dimension: dimensions, - FiltersObj: filtersToPayload(q.FiltersObj), + FiltersObj: filtersPointerToPayload(q.FiltersObj), SavedFilters: savedFiltersPayloads, MatrixBy: q.MatrixBy, CIDR: q.CIDR, @@ -247,7 +247,7 @@ func queryToPayload(q models.Query) (queryPayload, error) { }, nil } -func filtersToPayload(f *models.Filters) *filtersPayload { +func filtersPointerToPayload(f *models.Filters) *filtersPayload { if f == nil { return nil } diff --git a/kentikapi/internal/api_payloads/saved_filter.go b/kentikapi/internal/api_payloads/saved_filter.go index 0e44694d..e70acdc6 100644 --- a/kentikapi/internal/api_payloads/saved_filter.go +++ b/kentikapi/internal/api_payloads/saved_filter.go @@ -77,7 +77,7 @@ func SavedFilterToPayload(sf models.SavedFilter) savedFilterPayload { FilterLevel: sf.FilterLevel, CreatedDate: &sf.CreatedDate, UpdatedDate: &sf.UpdatedDate, - Filters: FiltersToPayload(sf.Filters), + Filters: filtersToPayload(sf.Filters), } } @@ -114,8 +114,7 @@ func (p filtersPayload) ToFilters() (models.Filters, error) { }, nil } -//nolint:revive // FiltersToPayload could be unexported but filtersToPayload already exists -func FiltersToPayload(f models.Filters) filtersPayload { +func filtersToPayload(f models.Filters) filtersPayload { var filterGroups []filterGroupsPayload for _, fg := range f.FilterGroups { filterGroups = append(filterGroups, filterGroupsToPayload(fg)) diff --git a/kentikapi/internal/resources/alerting.go b/kentikapi/internal/resources/alerting.go index b002cfa2..35a072ff 100644 --- a/kentikapi/internal/resources/alerting.go +++ b/kentikapi/internal/resources/alerting.go @@ -49,8 +49,8 @@ func (a *AlertingAPI) GetActiveAlerts(ctx context.Context, params models.AlertsQ return response.ToAlarms(), nil } -func (a *AlertingAPI) GetAlertsHistory(ctx context.Context, - params models.AlertsQueryParams) ([]models.HistoricalAlert, error) { +func (a *AlertingAPI) GetAlertsHistory(ctx context.Context, params models.AlertsQueryParams, +) ([]models.HistoricalAlert, error) { var response api_payloads.GetHistoricalAlertsResponse path := api_endpoints.GetAlertsHistoryPath(params.StartTime, params.EndTime, params.FilterBy, params.FilterVal, params.SortOrder, params.ShowMitigations, params.ShowAlarms, params.ShowMatches, params.LearningMode) diff --git a/kentikapi/internal/resources/custom_applications.go b/kentikapi/internal/resources/custom_applications.go index 8038e21b..97ccf8aa 100644 --- a/kentikapi/internal/resources/custom_applications.go +++ b/kentikapi/internal/resources/custom_applications.go @@ -31,8 +31,8 @@ func (a *CustomApplicationsAPI) GetAll(ctx context.Context) ([]models.CustomAppl } // Create new custom application. -func (a *CustomApplicationsAPI) Create(ctx context.Context, - customApplication models.CustomApplication) (*models.CustomApplication, error) { +func (a *CustomApplicationsAPI) Create(ctx context.Context, customApplication models.CustomApplication, +) (*models.CustomApplication, error) { payload := api_payloads.CustomApplicationToPayload(customApplication) request := api_payloads.CreateCustomApplicationRequest(payload) var response api_payloads.CreateCustomApplicationResponse @@ -45,13 +45,17 @@ func (a *CustomApplicationsAPI) Create(ctx context.Context, } // Update custom application. -//nolint:lll -func (a *CustomApplicationsAPI) Update(ctx context.Context, - customApplication models.CustomApplication) (*models.CustomApplication, error) { +func (a *CustomApplicationsAPI) Update(ctx context.Context, customApplication models.CustomApplication, +) (*models.CustomApplication, error) { payload := api_payloads.CustomApplicationToPayload(customApplication) request := api_payloads.UpdateCustomApplicationRequest(payload) var response api_payloads.UpdateCustomApplicationResponse - if err := a.UpdateAndValidate(ctx, api_endpoints.UpdateCustomApplication(customApplication.ID), request, &response); err != nil { + if err := a.UpdateAndValidate( + ctx, + api_endpoints.UpdateCustomApplication(customApplication.ID), + request, + &response, + ); err != nil { return nil, err } diff --git a/kentikapi/internal/resources/custom_dimensions.go b/kentikapi/internal/resources/custom_dimensions.go index c8b84f4b..2dd2ac47 100644 --- a/kentikapi/internal/resources/custom_dimensions.go +++ b/kentikapi/internal/resources/custom_dimensions.go @@ -102,10 +102,12 @@ func (a *populatorsAPI) Update(ctx context.Context, populator models.Populator) request := api_payloads.UpdatePopulatorRequest{Payload: payload} var response api_payloads.UpdatePopulatorResponse - if err := a.UpdateAndValidate(ctx, + if err := a.UpdateAndValidate( + ctx, api_endpoints.UpdatePopulator(populator.DimensionID, populator.ID), request, - &response); err != nil { + &response, + ); err != nil { return nil, err } diff --git a/kentikapi/internal/resources/devices_test.go b/kentikapi/internal/resources/devices_test.go index 8f7ce321..4d6657e3 100644 --- a/kentikapi/internal/resources/devices_test.go +++ b/kentikapi/internal/resources/devices_test.go @@ -1,4 +1,3 @@ -//nolint:dupl package resources_test import ( @@ -555,6 +554,7 @@ func TestUpdatetDeviceRouter(t *testing.T) { assert.Equal(models.DeviceSubtypePaloalto, device.DeviceSubType) } +//nolint:dupl func TestGetDevice(t *testing.T) { tests := []struct { name string diff --git a/kentikapi/internal/resources/my_kentik_portal.go b/kentikapi/internal/resources/my_kentik_portal.go index 58bb9aaa..2fd679f8 100644 --- a/kentikapi/internal/resources/my_kentik_portal.go +++ b/kentikapi/internal/resources/my_kentik_portal.go @@ -37,8 +37,8 @@ func (a *MyKentikPortalAPI) Get(ctx context.Context, tenantID models.ID) (*model return &tenant, err } -func (a *MyKentikPortalAPI) CreateTenantUser(ctx context.Context, - tenantID models.ID, userEmail string) (*models.TenantUser, error) { +func (a *MyKentikPortalAPI) CreateTenantUser(ctx context.Context, tenantID models.ID, userEmail string, +) (*models.TenantUser, error) { request := api_payloads.CreateTenantUserRequest{ User: api_payloads.CreateTenantUserPayload{ Email: userEmail, diff --git a/kentikapi/internal/resources/tags.go b/kentikapi/internal/resources/tags.go index 9878face..df18309c 100644 --- a/kentikapi/internal/resources/tags.go +++ b/kentikapi/internal/resources/tags.go @@ -1,4 +1,3 @@ -//nolint:dupl package resources import ( diff --git a/kentikapi/internal/resources/users.go b/kentikapi/internal/resources/users.go index 2fae0eb6..c25e9122 100644 --- a/kentikapi/internal/resources/users.go +++ b/kentikapi/internal/resources/users.go @@ -1,4 +1,3 @@ -//nolint:dupl package resources import ( diff --git a/kentikapi/models/device.go b/kentikapi/models/device.go index 29713aa8..22cd2100 100644 --- a/kentikapi/models/device.go +++ b/kentikapi/models/device.go @@ -12,8 +12,8 @@ type Device struct { DeviceSNMNPIP *string DeviceSNMPCommunity *string MinimizeSNMP *bool - DeviceBGPType *DeviceBGPType // Note: for DeviceBGPType = DeviceBGPTypeDevice, - // either DeviceBGPNeighborIP or DeviceBGPNeighborIPv6 is required + // Note: for DeviceBGPType = DeviceBGPTypeDevice, either DeviceBGPNeighborIP or DeviceBGPNeighborIPv6 is required + DeviceBGPType *DeviceBGPType DeviceBGPNeighborIP *string DeviceBGPNeighborIPv6 *string DeviceBGPNeighborASN *string diff --git a/kentikapi/tags_integration_test.go b/kentikapi/tags_integration_test.go index 03c9f759..28bc2347 100644 --- a/kentikapi/tags_integration_test.go +++ b/kentikapi/tags_integration_test.go @@ -1,4 +1,3 @@ -//nolint:dupl package kentikapi_test import ( @@ -82,6 +81,7 @@ func TestClient_GetAllTags(t *testing.T) { }, }, } + //nolint:dupl for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // arrange @@ -362,6 +362,7 @@ func TestClient_CreateTag(t *testing.T) { } } +//nolint:dupl func TestClient_UpdateTag(t *testing.T) { tests := []struct { name string @@ -492,6 +493,7 @@ func TestClient_UpdateTag(t *testing.T) { }, }, } + //nolint:dupl for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // arrange @@ -615,6 +617,7 @@ const testTagOneResponseJSON = `{ "vlans": "4001,4002,4003" }` +//nolint:dupl func newTestTagOne(t *testing.T) *models.Tag { return &models.Tag{ FlowTag: "APITEST-TAG-1", diff --git a/kentikapi/users_integration_test.go b/kentikapi/users_integration_test.go index 402cdf26..e8d11733 100644 --- a/kentikapi/users_integration_test.go +++ b/kentikapi/users_integration_test.go @@ -1,4 +1,3 @@ -//nolint:dupl package kentikapi_test import ( @@ -159,6 +158,7 @@ func TestClient_GetAllUsers(t *testing.T) { }}, }, } + //nolint:dupl for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // arrange @@ -668,6 +668,7 @@ func TestClient_UpdateUser(t *testing.T) { }, }, } + //nolint:dupl for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // arrange From 87b6b721d5a8b1fb80eedea0a32e5a2b64763b7e Mon Sep 17 00:00:00 2001 From: maciej palczynski Date: Fri, 10 Sep 2021 08:58:43 +0200 Subject: [PATCH 5/6] Implemented third batch of suggestions from review --- kentikapi/internal/api_payloads/query.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/kentikapi/internal/api_payloads/query.go b/kentikapi/internal/api_payloads/query.go index f27067bb..c063158d 100644 --- a/kentikapi/internal/api_payloads/query.go +++ b/kentikapi/internal/api_payloads/query.go @@ -147,11 +147,10 @@ type queryArrayItemPayload struct { IsOverlay *bool `json:"isOverlay,omitempty"` } -//nolint:nilerr func queryArrayItemToPayload(i models.QueryArrayItem) (queryArrayItemPayload, error) { query, err := queryToPayload(i.Query) if err != nil { - return queryArrayItemPayload{}, nil + return queryArrayItemPayload{}, err } return queryArrayItemPayload{ From 4fbe6ade73ce9ea4210fde4e495ef9fc4fae49b9 Mon Sep 17 00:00:00 2001 From: maciej palczynski Date: Fri, 10 Sep 2021 12:34:08 +0200 Subject: [PATCH 6/6] Implemented third batch of suggestions from review --- .golangci.yml | 8 -------- kentikapi/internal/resources/tags.go | 1 + kentikapi/internal/resources/users.go | 1 + 3 files changed, 2 insertions(+), 8 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 8e7bcd31..1be17acc 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -23,14 +23,6 @@ issues: - gochecknoglobals - lll - gomnd - # tags.go and users.go are called by dupl in entirety. Nolints on package level are not recommended, - # so this is a workaround. - - path: kentikapi/internal/resources/tags.go - linters: - - dupl - - path: kentikapi/internal/resources/users.go - linters: - - dupl # Disabled linters: # - cyclop - duplicates functionality of gocyclo diff --git a/kentikapi/internal/resources/tags.go b/kentikapi/internal/resources/tags.go index df18309c..9878face 100644 --- a/kentikapi/internal/resources/tags.go +++ b/kentikapi/internal/resources/tags.go @@ -1,3 +1,4 @@ +//nolint:dupl package resources import ( diff --git a/kentikapi/internal/resources/users.go b/kentikapi/internal/resources/users.go index c25e9122..2fae0eb6 100644 --- a/kentikapi/internal/resources/users.go +++ b/kentikapi/internal/resources/users.go @@ -1,3 +1,4 @@ +//nolint:dupl package resources import (