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..1be17acc 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,10 +1,124 @@ +# 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: + # 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) + 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 - 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 +# - 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, TODO: ignore false-positives (interfaces, internal imports) and adjust the code to comply +# - 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 + - gomnd + - gomodguard + - goprintffuncname + - gosec + - gosimple + - govet + - ifshort + - importas + - ineffassign + - lll + - makezero + - misspell + - nakedret + - nestif + - nilerr + - noctx + - nolintlint + - predeclared + - revive + - rowserrcheck + - sqlclosecheck + - staticcheck + - structcheck + - stylecheck + - testpackage + - tparallel + - typecheck + - unconvert + - unparam + - unused + - varcheck + - wastedassign + - whitespace + +linters-settings: + 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: 10 + govet: + disable: + # Reordering struct fields may decrease readability + - fieldalignment + enable-all: true + lll: + # 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 a8cadce6..b67b0ef7 100644 --- a/apiv6/kentikapi/client.go +++ b/apiv6/kentikapi/client.go @@ -6,6 +6,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" @@ -16,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. @@ -52,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 ca1ac4c0..8099460e 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" @@ -181,10 +182,12 @@ 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 t.Logf("Got result: %v, httpResp: %v, err: %v", result, httpResp, err) @@ -197,7 +200,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 +228,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 +347,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 +375,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..1cc1098c 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" ) @@ -24,12 +24,13 @@ import ( func TestRetryingClient_Do_ReturnsHTTPTransportError(t *testing.T) { // arrange - c := NewRetryingClient(ClientConfig{}) + c := httputil.NewRetryingClient(httputil.ClientConfig{}) req, err := retryablehttp.NewRequest(http.MethodGet, "https://invalid.url", nil) require.NoError(t, err) // act + //nolint:bodyclose resp, err := c.Do(req.WithContext(context.Background())) // assert @@ -75,13 +76,12 @@ func TestRetryingClientWithSpyHTTPTransport_Do(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // 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), @@ -92,6 +92,7 @@ func TestRetryingClientWithSpyHTTPTransport_Do(t *testing.T) { require.NoError(t, err) // act + //nolint:bodyclose resp, err := c.Do(req.WithContext(context.Background())) // assert diff --git a/apiv6/localhost_apiserver/cloudexport/go/routers.go b/apiv6/localhost_apiserver/cloudexport/go/routers.go index b14bc93b..b6678fc9 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 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/apiv6/localhost_apiserver/synthetics/go/routers.go b/apiv6/localhost_apiserver/synthetics/go/routers.go index 1237fa33..09b7ec13 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 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..3ba0edce 100644 --- a/kentikapi/client.go +++ b/kentikapi/client.go @@ -3,7 +3,7 @@ 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/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 } @@ -52,19 +52,19 @@ func NewClient(c Config) *Client { 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_connection/rest_client.go b/kentikapi/internal/api_connection/rest_client.go index 12ac2362..5271ba4e 100644 --- a/kentikapi/internal/api_connection/rest_client.go +++ b/kentikapi/internal/api_connection/rest_client.go @@ -5,18 +5,20 @@ import ( "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/api_connection/stub_transport.go index 1848103e..3764242b 100644 --- a/kentikapi/internal/api_connection/stub_transport.go +++ b/kentikapi/internal/api_connection/stub_transport.go @@ -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_endpoints/alerting.go b/kentikapi/internal/api_endpoints/alerting.go index 3de6a7d4..07f623d2 100644 --- a/kentikapi/internal/api_endpoints/alerting.go +++ b/kentikapi/internal/api_endpoints/alerting.go @@ -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_payloads/custom_application.go b/kentikapi/internal/api_payloads/custom_application.go index 94eeb4bc..d72f7161 100644 --- a/kentikapi/internal/api_payloads/custom_application.go +++ b/kentikapi/internal/api_payloads/custom_application.go @@ -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/api_payloads/custom_dimension.go index 8c1747c3..8fc977a6 100644 --- a/kentikapi/internal/api_payloads/custom_dimension.go +++ b/kentikapi/internal/api_payloads/custom_dimension.go @@ -4,7 +4,7 @@ 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/api_payloads/device.go index a71d16c7..8d1eff5b 100644 --- a/kentikapi/internal/api_payloads/device.go +++ b/kentikapi/internal/api_payloads/device.go @@ -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/api_payloads/device_label.go index 322a47c7..59c57400 100644 --- a/kentikapi/internal/api_payloads/device_label.go +++ b/kentikapi/internal/api_payloads/device_label.go @@ -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/api_payloads/interface.go index af163314..3e8ad3b7 100644 --- a/kentikapi/internal/api_payloads/interface.go +++ b/kentikapi/internal/api_payloads/interface.go @@ -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 - 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"` + 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 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/api_payloads/plan.go index fdef22ce..bfc6b695 100644 --- a/kentikapi/internal/api_payloads/plan.go +++ b/kentikapi/internal/api_payloads/plan.go @@ -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/api_payloads/populator.go index ea2d89de..92bd53df 100644 --- a/kentikapi/internal/api_payloads/populator.go +++ b/kentikapi/internal/api_payloads/populator.go @@ -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/api_payloads/query.go index 53a22e21..c063158d 100644 --- a/kentikapi/internal/api_payloads/query.go +++ b/kentikapi/internal/api_payloads/query.go @@ -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 { @@ -149,7 +150,7 @@ type queryArrayItemPayload struct { func queryArrayItemToPayload(i models.QueryArrayItem) (queryArrayItemPayload, error) { query, err := queryToPayload(i.Query) if err != nil { - return queryArrayItemPayload{}, nil + return queryArrayItemPayload{}, err } return queryArrayItemPayload{ @@ -161,32 +162,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 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"` + 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) { @@ -217,7 +219,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, @@ -244,7 +246,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 } @@ -252,7 +254,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 +290,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/api_payloads/query_test.go index 90d5136d..6532ec65 100644 --- a/kentikapi/internal/api_payloads/query_test.go +++ b/kentikapi/internal/api_payloads/query_test.go @@ -109,7 +109,7 @@ func TestFormatQueryTimeNonNil(t *testing.T) { func TestFormatQueryTimeNil(t *testing.T) { // arrange - var datetime *time.Time = nil + var datetime *time.Time // act queryTime := api_payloads.FormatQueryTime(datetime) diff --git a/kentikapi/internal/api_payloads/saved_filter.go b/kentikapi/internal/api_payloads/saved_filter.go index b93f6ee8..e70acdc6 100644 --- a/kentikapi/internal/api_payloads/saved_filter.go +++ b/kentikapi/internal/api_payloads/saved_filter.go @@ -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), @@ -76,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), } } @@ -113,10 +114,10 @@ func (p filtersPayload) ToFilters() (models.Filters, error) { }, nil } -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)) + filterGroups = append(filterGroups, filterGroupsToPayload(fg)) } return filtersPayload{ @@ -152,10 +153,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 +185,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/api_payloads/site.go index 7d94f4fb..0997b50b 100644 --- a/kentikapi/internal/api_payloads/site.go +++ b/kentikapi/internal/api_payloads/site.go @@ -5,7 +5,7 @@ import ( "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/api_payloads/tag.go index 597e5785..31ea8809 100644 --- a/kentikapi/internal/api_payloads/tag.go +++ b/kentikapi/internal/api_payloads/tag.go @@ -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/types.go b/kentikapi/internal/api_payloads/types.go index 2ca8235c..a1e20093 100644 --- a/kentikapi/internal/api_payloads/types.go +++ b/kentikapi/internal/api_payloads/types.go @@ -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/api_payloads/types_test.go index fb0c059b..61cca0e8 100644 --- a/kentikapi/internal/api_payloads/types_test.go +++ b/kentikapi/internal/api_payloads/types_test.go @@ -1,45 +1,46 @@ -package api_payloads +package api_payloads_test import ( "encoding/json" "testing" + "github.com/kentik/community_sdk_golang/kentikapi/internal/api_payloads" "github.com/stretchr/testify/assert" ) func TestBoolAsString_UnmarshalJSON(t *testing.T) { tests := []struct { input string - expectedResult BoolAsStringOrInt + expectedResult api_payloads.BoolAsStringOrInt expectedError bool }{ { input: `true`, - expectedResult: BoolAsStringOrInt(true), + expectedResult: api_payloads.BoolAsStringOrInt(true), }, { input: `false`, - expectedResult: BoolAsStringOrInt(false), + expectedResult: api_payloads.BoolAsStringOrInt(false), }, { input: `"true"`, - expectedResult: BoolAsStringOrInt(true), + expectedResult: api_payloads.BoolAsStringOrInt(true), }, { input: `"True"`, - expectedResult: BoolAsStringOrInt(true), + expectedResult: api_payloads.BoolAsStringOrInt(true), }, { input: `"false"`, - expectedResult: BoolAsStringOrInt(false), + expectedResult: api_payloads.BoolAsStringOrInt(false), }, { input: `"False"`, - expectedResult: BoolAsStringOrInt(false), + expectedResult: api_payloads.BoolAsStringOrInt(false), }, { input: `"invalid-string"`, expectedError: true, }, { input: `1`, - expectedResult: BoolAsStringOrInt(true), + expectedResult: api_payloads.BoolAsStringOrInt(true), }, { input: `0`, - expectedResult: BoolAsStringOrInt(false), + expectedResult: api_payloads.BoolAsStringOrInt(false), }, { input: `1.0`, expectedError: true, @@ -50,7 +51,7 @@ func TestBoolAsString_UnmarshalJSON(t *testing.T) { } for _, tt := range tests { t.Run(tt.input, func(t *testing.T) { - var result BoolAsStringOrInt + var result api_payloads.BoolAsStringOrInt err := json.Unmarshal([]byte(tt.input), &result) if tt.expectedError { diff --git a/kentikapi/internal/api_payloads/user.go b/kentikapi/internal/api_payloads/user.go index fed5a1d1..d1998ae3 100644 --- a/kentikapi/internal/api_payloads/user.go +++ b/kentikapi/internal/api_payloads/user.go @@ -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/api_resources/alerting.go b/kentikapi/internal/resources/alerting.go similarity index 94% rename from kentikapi/internal/api_resources/alerting.go rename to kentikapi/internal/resources/alerting.go index ed64dca1..35a072ff 100644 --- a/kentikapi/internal/api_resources/alerting.go +++ b/kentikapi/internal/resources/alerting.go @@ -1,4 +1,4 @@ -package api_resources +package resources import ( "context" @@ -14,7 +14,7 @@ type AlertingAPI struct { BaseAPI } -// NewAlertingAPI is constructor +// NewAlertingAPI is constructor. func NewAlertingAPI(transport api_connection.Transport) *AlertingAPI { return &AlertingAPI{ BaseAPI{Transport: transport}, @@ -49,7 +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/api_resources/alerting_test.go b/kentikapi/internal/resources/alerting_test.go similarity index 87% rename from kentikapi/internal/api_resources/alerting_test.go rename to kentikapi/internal/resources/alerting_test.go index 38439094..7e698aeb 100644 --- a/kentikapi/internal/api_resources/alerting_test.go +++ b/kentikapi/internal/resources/alerting_test.go @@ -1,4 +1,4 @@ -package api_resources_test +package resources_test import ( "context" @@ -6,13 +6,16 @@ import ( "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/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) { createResponsePayload := ` @@ -24,7 +27,7 @@ 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) + alertingAPI := resources.NewAlertingAPI(transport) mm := models.ManualMitigation{ IPCidr: "192.168.0.0/24", PlatformID: 1234, @@ -77,7 +80,7 @@ func TestGetActiveAlerts(t *testing.T) { } ]` transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - alertingAPI := api_resources.NewAlertingAPI(transport) + alertingAPI := resources.NewAlertingAPI(transport) alarmEndStr := "0000-00-00 00:00:00" expected := []models.Alarm{ @@ -127,7 +130,12 @@ 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) { @@ -167,7 +175,7 @@ func TestGetAlertsHistory(t *testing.T) { } ]` transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - alertingAPI := api_resources.NewAlertingAPI(transport) + alertingAPI := resources.NewAlertingAPI(transport) dateStr := "2021-01-19 13:50:00" expected := []models.HistoricalAlert{ @@ -216,5 +224,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 91% rename from kentikapi/internal/api_resources/base.go rename to kentikapi/internal/resources/base.go index cb508afc..47b7553e 100644 --- a/kentikapi/internal/api_resources/base.go +++ b/kentikapi/internal/resources/base.go @@ -1,4 +1,4 @@ -package api_resources +package resources import ( "context" @@ -9,13 +9,13 @@ import ( "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 } // 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/api_resources/custom_applications.go b/kentikapi/internal/resources/custom_applications.go similarity index 79% rename from kentikapi/internal/api_resources/custom_applications.go rename to kentikapi/internal/resources/custom_applications.go index 486a55be..97ccf8aa 100644 --- a/kentikapi/internal/api_resources/custom_applications.go +++ b/kentikapi/internal/resources/custom_applications.go @@ -1,4 +1,4 @@ -package api_resources +package resources import ( "context" @@ -13,14 +13,14 @@ type CustomApplicationsAPI struct { BaseAPI } -// NewCustomApplicationsAPI is constructor +// NewCustomApplicationsAPI is constructor. func NewCustomApplicationsAPI(transport api_connection.Transport) *CustomApplicationsAPI { return &CustomApplicationsAPI{ BaseAPI{Transport: transport}, } } -// GetAll custom applications +// 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 { @@ -30,8 +30,9 @@ func (a *CustomApplicationsAPI) GetAll(ctx context.Context) ([]models.CustomAppl return response.ToCustomApplications() } -// Create new custom application -func (a *CustomApplicationsAPI) Create(ctx context.Context, customApplication models.CustomApplication) (*models.CustomApplication, error) { +// 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 @@ -43,12 +44,18 @@ func (a *CustomApplicationsAPI) Create(ctx context.Context, customApplication mo return &result, err } -// Update custom application -func (a *CustomApplicationsAPI) Update(ctx context.Context, customApplication models.CustomApplication) (*models.CustomApplication, error) { +// 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 { + if err := a.UpdateAndValidate( + ctx, + api_endpoints.UpdateCustomApplication(customApplication.ID), + request, + &response, + ); err != nil { return nil, err } @@ -56,7 +63,7 @@ func (a *CustomApplicationsAPI) Update(ctx context.Context, customApplication mo return &result, err } -// Delete custom application +// 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_applications_test.go b/kentikapi/internal/resources/custom_applications_test.go similarity index 94% rename from kentikapi/internal/api_resources/custom_applications_test.go rename to kentikapi/internal/resources/custom_applications_test.go index 61062db9..9768c22d 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" @@ -7,7 +7,7 @@ import ( "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/resources" "github.com/kentik/community_sdk_golang/kentikapi/internal/utils" "github.com/kentik/community_sdk_golang/kentikapi/models" "github.com/stretchr/testify/assert" @@ -45,7 +45,7 @@ func TestGetAll(t *testing.T) { } ]` transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - applicationsAPI := api_resources.NewCustomApplicationsAPI(transport) + applicationsAPI := resources.NewCustomApplicationsAPI(transport) // act applications, err := applicationsAPI.GetAll(context.Background()) @@ -89,7 +89,7 @@ func TestCreateCustomApplication(t *testing.T) { "company_id": "74333" }` transport := &api_connection.StubTransport{ResponseBody: createResponsePayload} - applicationsAPI := api_resources.NewCustomApplicationsAPI(transport) + applicationsAPI := resources.NewCustomApplicationsAPI(transport) app := models.NewCustomApplication("apitest-customapp-1") models.SetOptional(&app.Description, "Testing custom application api") @@ -145,7 +145,7 @@ func TestUpdateCustomApplication(t *testing.T) { "edate": "2020-12-11T07:07:20.968Z" }` transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} - applicationsAPI := api_resources.NewCustomApplicationsAPI(transport) + applicationsAPI := resources.NewCustomApplicationsAPI(transport) appID := models.ID(207) app := models.CustomApplication{ @@ -191,7 +191,7 @@ func TestDeleteCustomApplication(t *testing.T) { // arrange deleteResponsePayload := "" // deleting custom application responds with empty body transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} - appliationsAPI := api_resources.NewCustomApplicationsAPI(transport) + appliationsAPI := resources.NewCustomApplicationsAPI(transport) // act appID := models.ID(42) diff --git a/kentikapi/internal/api_resources/custom_dimensions.go b/kentikapi/internal/resources/custom_dimensions.go similarity index 82% rename from kentikapi/internal/api_resources/custom_dimensions.go rename to kentikapi/internal/resources/custom_dimensions.go index c26651f6..2dd2ac47 100644 --- a/kentikapi/internal/api_resources/custom_dimensions.go +++ b/kentikapi/internal/resources/custom_dimensions.go @@ -1,4 +1,4 @@ -package api_resources +package resources import ( "context" @@ -14,7 +14,7 @@ type CustomDimensionsAPI struct { Populators *populatorsAPI } -// NewCustomDimensionsAPI is constructor +// NewCustomDimensionsAPI is constructor. func NewCustomDimensionsAPI(transport api_connection.Transport) *CustomDimensionsAPI { return &CustomDimensionsAPI{ BaseAPI{Transport: transport}, @@ -22,7 +22,7 @@ func NewCustomDimensionsAPI(transport api_connection.Transport) *CustomDimension } } -// GetAll custom dimensions +// 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 { @@ -32,7 +32,7 @@ func (a *CustomDimensionsAPI) GetAll(ctx context.Context) ([]models.CustomDimens return response.ToCustomDimensions(), nil } -// Get custom dimension with given ID +// 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 { @@ -43,8 +43,9 @@ func (a *CustomDimensionsAPI) Get(ctx context.Context, id models.ID) (*models.Cu return &result, nil } -// Create new custom dimension -func (a *CustomDimensionsAPI) Create(ctx context.Context, customDimension models.CustomDimension) (*models.CustomDimension, error) { +// 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) @@ -57,8 +58,9 @@ func (a *CustomDimensionsAPI) Create(ctx context.Context, customDimension models return &result, nil } -// Update custom dimension -func (a *CustomDimensionsAPI) Update(ctx context.Context, customDimension models.CustomDimension) (*models.CustomDimension, error) { +// 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) @@ -71,7 +73,7 @@ func (a *CustomDimensionsAPI) Update(ctx context.Context, customDimension models return &result, nil } -// Delete custom dimension +// Delete custom dimension. func (a *CustomDimensionsAPI) Delete(ctx context.Context, id models.ID) error { return a.DeleteAndValidate(ctx, api_endpoints.DeleteCustomDimension(id), nil) } @@ -80,7 +82,7 @@ type populatorsAPI struct { BaseAPI } -// Create new populator +// Create new populator. func (a *populatorsAPI) Create(ctx context.Context, populator models.Populator) (*models.Populator, error) { payload := api_payloads.PopulatorToPayload(populator) @@ -94,13 +96,18 @@ func (a *populatorsAPI) Create(ctx context.Context, populator models.Populator) return &result, nil } -// Update populator +// 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 { + if err := a.UpdateAndValidate( + ctx, + api_endpoints.UpdatePopulator(populator.DimensionID, populator.ID), + request, + &response, + ); err != nil { return nil, err } @@ -108,7 +115,7 @@ func (a *populatorsAPI) Update(ctx context.Context, populator models.Populator) return &result, nil } -// Delete populator +// 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/custom_dimensions_test.go b/kentikapi/internal/resources/custom_dimensions_test.go similarity index 96% rename from kentikapi/internal/api_resources/custom_dimensions_test.go rename to kentikapi/internal/resources/custom_dimensions_test.go index 2ac60550..50a581c9 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" @@ -8,7 +8,7 @@ import ( "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/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" @@ -30,8 +30,12 @@ func TestCreateCustomDimension(t *testing.T) { } }` transport := &api_connection.StubTransport{ResponseBody: createResponsePayload} - customDimensionsAPI := api_resources.NewCustomDimensionsAPI(transport) - dimension := models.NewCustomDimension("c_testapi_dimension_1", "dimension_display_name", models.CustomDimensionTypeStr) + customDimensionsAPI := resources.NewCustomDimensionsAPI(transport) + dimension := models.NewCustomDimension( + "c_testapi_dimension_1", + "dimension_display_name", + models.CustomDimensionTypeStr, + ) // act created, err := customDimensionsAPI.Create(context.Background(), *dimension) @@ -71,7 +75,7 @@ func TestUpdateCustomDimension(t *testing.T) { } }` transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} - customDimensionsAPI := api_resources.NewCustomDimensionsAPI(transport) + customDimensionsAPI := resources.NewCustomDimensionsAPI(transport) dimensionID := models.ID(42) dimension := models.CustomDimension{ID: dimensionID, DisplayName: "dimension_display_name2"} @@ -310,7 +314,7 @@ func TestGetCustomDimension(t *testing.T) { t.Run(tt.name, func(t *testing.T) { // arrange transport := &api_connection.StubTransport{ResponseBody: tt.responseBody} - customDimensionsAPI := api_resources.NewCustomDimensionsAPI(transport) + customDimensionsAPI := resources.NewCustomDimensionsAPI(transport) dimensionID := 42 // act @@ -372,7 +376,7 @@ func TestGetAllCustomDimensions(t *testing.T) { ] }` transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - customDimensionsAPI := api_resources.NewCustomDimensionsAPI(transport) + customDimensionsAPI := resources.NewCustomDimensionsAPI(transport) // act dimensions, err := customDimensionsAPI.GetAll(context.Background()) @@ -419,7 +423,7 @@ func TestDeleteCustomDimension(t *testing.T) { // arrange deleteResponsePayload := "" // deleting device responds with empty body transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} - customDimensionsAPI := api_resources.NewCustomDimensionsAPI(transport) + customDimensionsAPI := resources.NewCustomDimensionsAPI(transport) // act dimensionID := models.ID(42) @@ -470,9 +474,14 @@ func TestCreatePopulator(t *testing.T) { } }` transport := &api_connection.StubTransport{ResponseBody: createResponsePayload} - customDimensionsAPI := api_resources.NewCustomDimensionsAPI(transport) + 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") @@ -579,7 +588,7 @@ func TestUpdatePopulator(t *testing.T) { }` transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} - customDimensionsAPI := api_resources.NewCustomDimensionsAPI(transport) + customDimensionsAPI := resources.NewCustomDimensionsAPI(transport) dimensionID := models.ID(24001) populatorID := models.ID(1510862280) @@ -637,7 +646,7 @@ func TestDeletePopulator(t *testing.T) { // arrange deleteResponsePayload := "" // deleting device responds with empty body transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} - customDimensionsAPI := api_resources.NewCustomDimensionsAPI(transport) + customDimensionsAPI := resources.NewCustomDimensionsAPI(transport) // act dimensionID := models.ID(42) diff --git a/kentikapi/internal/api_resources/device_labels.go b/kentikapi/internal/resources/device_labels.go similarity index 93% rename from kentikapi/internal/api_resources/device_labels.go rename to kentikapi/internal/resources/device_labels.go index 14d692c0..f024688a 100644 --- a/kentikapi/internal/api_resources/device_labels.go +++ b/kentikapi/internal/resources/device_labels.go @@ -1,4 +1,4 @@ -package api_resources +package resources import ( "context" @@ -14,14 +14,14 @@ type DeviceLabelsAPI struct { BaseAPI } -// NewDeviceLabelsAPIis constructor +// NewDeviceLabelsAPI is constructor. func NewDeviceLabelsAPI(transport api_connection.Transport) *DeviceLabelsAPI { return &DeviceLabelsAPI{ BaseAPI{Transport: transport}, } } -// GetAll labels +// 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 { @@ -31,7 +31,7 @@ func (a *DeviceLabelsAPI) GetAll(ctx context.Context) ([]models.DeviceLabel, err return response.ToDeviceLabels() } -// Get label with given ID +// 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 { @@ -42,7 +42,7 @@ func (a *DeviceLabelsAPI) Get(ctx context.Context, id models.ID) (*models.Device return &device, err } -// Create new label +// Create new label. func (a *DeviceLabelsAPI) Create(ctx context.Context, label models.DeviceLabel) (*models.DeviceLabel, error) { payload := api_payloads.DeviceLabelToPayload(label) @@ -56,7 +56,7 @@ func (a *DeviceLabelsAPI) Create(ctx context.Context, label models.DeviceLabel) return &result, err } -// Update label +// Update label. func (a *DeviceLabelsAPI) Update(ctx context.Context, label models.DeviceLabel) (*models.DeviceLabel, error) { payload := api_payloads.DeviceLabelToPayload(label) @@ -70,7 +70,7 @@ func (a *DeviceLabelsAPI) Update(ctx context.Context, label models.DeviceLabel) return &result, err } -// Delete label +// 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 { diff --git a/kentikapi/internal/api_resources/device_labels_test.go b/kentikapi/internal/resources/device_labels_test.go similarity index 95% rename from kentikapi/internal/api_resources/device_labels_test.go rename to kentikapi/internal/resources/device_labels_test.go index 121d4ec1..4378c0fd 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" @@ -7,7 +7,7 @@ import ( "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/resources" "github.com/kentik/community_sdk_golang/kentikapi/internal/utils" "github.com/kentik/community_sdk_golang/kentikapi/models" "github.com/stretchr/testify/assert" @@ -29,7 +29,7 @@ func TestCreateDeviceLabel(t *testing.T) { "updated_date": "2018-05-16T20:21:10.406Z" }` transport := &api_connection.StubTransport{ResponseBody: createResponsePayload} - labelsAPI := api_resources.NewDeviceLabelsAPI(transport) + labelsAPI := resources.NewDeviceLabelsAPI(transport) label := models.NewDeviceLabel("apitest-device_label-1", "#00FF00") // act @@ -70,7 +70,7 @@ func TestUpdateDeviceLabel(t *testing.T) { "updated_date": "2018-06-16T20:21:10.406Z" }` transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} - labelsAPI := api_resources.NewDeviceLabelsAPI(transport) + labelsAPI := resources.NewDeviceLabelsAPI(transport) label := models.DeviceLabel{Name: "apitest-device_label-one", Color: "#AA00FF"} label.ID = models.ID(42) @@ -119,7 +119,7 @@ func TestGetLabel(t *testing.T) { "updated_date": "2018-05-16T20:21:10.406Z" }` transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - labelsAPI := api_resources.NewDeviceLabelsAPI(transport) + labelsAPI := resources.NewDeviceLabelsAPI(transport) labelID := models.ID(32) // act @@ -187,7 +187,7 @@ func TestGetAllLabels(t *testing.T) { } ]` transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - labelsAPI := api_resources.NewDeviceLabelsAPI(transport) + labelsAPI := resources.NewDeviceLabelsAPI(transport) // act labels, err := labelsAPI.GetAll(context.Background()) @@ -234,7 +234,7 @@ func TestDeleteDeviceLabel(t *testing.T) { "success": true }` transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} - labelsAPI := api_resources.NewDeviceLabelsAPI(transport) + labelsAPI := resources.NewDeviceLabelsAPI(transport) // act labelID := models.ID(42) diff --git a/kentikapi/internal/api_resources/devices.go b/kentikapi/internal/resources/devices.go similarity index 88% rename from kentikapi/internal/api_resources/devices.go rename to kentikapi/internal/resources/devices.go index bb533689..cb364861 100644 --- a/kentikapi/internal/api_resources/devices.go +++ b/kentikapi/internal/resources/devices.go @@ -1,4 +1,4 @@ -package api_resources +package resources import ( "context" @@ -14,7 +14,7 @@ type DevicesAPI struct { Interfaces *interfacesAPI } -// NewDevicesAPI is constructor +// NewDevicesAPI is constructor. func NewDevicesAPI(transport api_connection.Transport) *DevicesAPI { return &DevicesAPI{ BaseAPI{Transport: transport}, @@ -22,7 +22,7 @@ func NewDevicesAPI(transport api_connection.Transport) *DevicesAPI { } } -// GetAll devices +// 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 { @@ -32,7 +32,7 @@ func (a *DevicesAPI) GetAll(ctx context.Context) ([]models.Device, error) { return response.ToDevices() } -// Get device with given ID +// 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 { @@ -43,7 +43,7 @@ func (a *DevicesAPI) Get(ctx context.Context, id models.ID) (*models.Device, err return &device, err } -// Create new device +// 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 @@ -55,7 +55,7 @@ func (a *DevicesAPI) Create(ctx context.Context, device models.Device) (*models. return &result, err } -// Update device +// 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 @@ -74,7 +74,7 @@ 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 +// 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) @@ -91,7 +91,7 @@ type interfacesAPI struct { BaseAPI } -// GetAll interfaces of given device +// 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 { @@ -101,7 +101,7 @@ func (a *interfacesAPI) GetAll(ctx context.Context, deviceID models.ID) ([]model return response.ToInterfaces() } -// Get interface of given device with given ID +// 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 { @@ -112,7 +112,7 @@ func (a *interfacesAPI) Get(ctx context.Context, deviceID, interfaceID models.ID return &intf, err } -// Create new interface under given device +// 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 { @@ -121,7 +121,7 @@ func (a *interfacesAPI) Create(ctx context.Context, intf models.Interface) (*mod request := api_payloads.CreateInterfaceRequest(payload) var response api_payloads.CreateInterfaceResponse - if err := a.PostAndValidate(ctx, api_endpoints.CreateInterface(intf.DeviceID), request, &response); err != nil { + if err = a.PostAndValidate(ctx, api_endpoints.CreateInterface(intf.DeviceID), request, &response); err != nil { return nil, err } @@ -129,12 +129,12 @@ func (a *interfacesAPI) Create(ctx context.Context, intf models.Interface) (*mod return &result, err } -// Delete interface +// 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 +// Update interface. func (a *interfacesAPI) Update(ctx context.Context, intf models.Interface) (*models.Interface, error) { payload, err := api_payloads.InterfaceToPayload(intf) if err != nil { @@ -143,7 +143,7 @@ func (a *interfacesAPI) Update(ctx context.Context, intf models.Interface) (*mod 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 { + if err = a.UpdateAndValidate(ctx, api_endpoints.UpdateInterface(intf.DeviceID, intf.ID), request, &response); err != nil { return nil, err } diff --git a/kentikapi/internal/api_resources/devices_test.go b/kentikapi/internal/resources/devices_test.go similarity index 97% rename from kentikapi/internal/api_resources/devices_test.go rename to kentikapi/internal/resources/devices_test.go index bb6d5603..4d6657e3 100644 --- a/kentikapi/internal/api_resources/devices_test.go +++ b/kentikapi/internal/resources/devices_test.go @@ -1,4 +1,4 @@ -package api_resources_test +package resources_test import ( "context" @@ -8,7 +8,7 @@ import ( "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/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" @@ -95,7 +95,7 @@ func TestCreateDeviceRouter(t *testing.T) { } }` transport := &api_connection.StubTransport{ResponseBody: createResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + devicesAPI := resources.NewDevicesAPI(transport) // act snmpv3conf := models.NewSNMPv3Conf("John") @@ -276,7 +276,7 @@ func TestCreateDeviceDNS(t *testing.T) { } }` transport := &api_connection.StubTransport{ResponseBody: createResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + devicesAPI := resources.NewDevicesAPI(transport) // act dns := models.NewDeviceDNS( @@ -439,7 +439,7 @@ func TestUpdatetDeviceRouter(t *testing.T) { } }` transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + devicesAPI := resources.NewDevicesAPI(transport) // act snmpv3conf := models.NewSNMPv3Conf("John") @@ -554,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 @@ -800,8 +801,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", @@ -1082,7 +1083,7 @@ func TestGetDevice(t *testing.T) { t.Run(tt.name, func(t *testing.T) { // arrange transport := &api_connection.StubTransport{ResponseBody: tt.responseBody} - devicesAPI := api_resources.NewDevicesAPI(transport) + devicesAPI := resources.NewDevicesAPI(transport) deviceID := 43 // act @@ -1277,7 +1278,7 @@ func TestGetAllDevices(t *testing.T) { ] }` transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + devicesAPI := resources.NewDevicesAPI(transport) // act devices, err := devicesAPI.GetAll(context.Background()) @@ -1325,8 +1326,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) @@ -1378,7 +1379,7 @@ func TestDeleteDevice(t *testing.T) { // arrange deleteResponsePayload := "" // deleting device responds with empty body transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + devicesAPI := resources.NewDevicesAPI(transport) // act deviceID := models.ID(42) @@ -1429,7 +1430,7 @@ func TestApplyLabels(t *testing.T) { ] }` transport := &api_connection.StubTransport{ResponseBody: applyLabelsResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + devicesAPI := resources.NewDevicesAPI(transport) // act deviceID := models.ID(42) @@ -1498,7 +1499,7 @@ func TestGetInterfaceMinimal(t *testing.T) { } }` transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + devicesAPI := resources.NewDevicesAPI(transport) // act deviceID := models.ID(42) @@ -1547,7 +1548,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 +1558,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", @@ -1601,7 +1602,7 @@ func TestGetInterfaceFull(t *testing.T) { } }` transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + devicesAPI := resources.NewDevicesAPI(transport) // act deviceID := models.ID(42) @@ -1623,13 +1624,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) @@ -1664,7 +1665,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 +1675,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 +1723,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 +1763,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": "", @@ -1789,7 +1790,7 @@ func TestGetAllInterfaces(t *testing.T) { } ]` transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + devicesAPI := resources.NewDevicesAPI(transport) // act deviceID := models.ID(42) @@ -1812,13 +1813,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) @@ -1857,7 +1858,7 @@ func TestCreateInterfaceMinimal(t *testing.T) { "id": "43" }` transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + devicesAPI := resources.NewDevicesAPI(transport) // act deviceID := models.ID(42) @@ -1902,7 +1903,7 @@ func TestCreateInterfaceFull(t *testing.T) { 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", @@ -1926,7 +1927,7 @@ func TestCreateInterfaceFull(t *testing.T) { ] }` transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + devicesAPI := resources.NewDevicesAPI(transport) // act vrf := models.NewVRFAttributes( @@ -1945,7 +1946,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 +1965,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 +1991,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) @@ -2001,7 +2002,7 @@ func TestDeleteInterface(t *testing.T) { // arrange deleteResponsePayload := "{}" transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + devicesAPI := resources.NewDevicesAPI(transport) // act deviceID := models.ID(42) @@ -2026,7 +2027,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": "", @@ -2052,7 +2053,7 @@ func TestUpdateInterfaceMinimal(t *testing.T) { "initial_interface_ip_netmask": null }` transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + devicesAPI := resources.NewDevicesAPI(transport) // act deviceID := models.ID(42) @@ -2081,7 +2082,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) @@ -2103,7 +2104,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": "", @@ -2129,7 +2130,7 @@ func TestUpdateInterfaceFull(t *testing.T) { "initial_interface_ip_netmask": null }` transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} - devicesAPI := api_resources.NewDevicesAPI(transport) + devicesAPI := resources.NewDevicesAPI(transport) // act vrf := models.NewVRFAttributes( @@ -2148,7 +2149,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 +2165,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 +2186,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/api_resources/my_kentik_portal.go b/kentikapi/internal/resources/my_kentik_portal.go similarity index 93% rename from kentikapi/internal/api_resources/my_kentik_portal.go rename to kentikapi/internal/resources/my_kentik_portal.go index 8d64aac3..2fd679f8 100644 --- a/kentikapi/internal/api_resources/my_kentik_portal.go +++ b/kentikapi/internal/resources/my_kentik_portal.go @@ -1,4 +1,4 @@ -package api_resources +package resources import ( "context" @@ -27,7 +27,7 @@ func (a *MyKentikPortalAPI) GetAll(ctx context.Context) ([]models.Tenant, error) return response.ToTenants() } -// Get Tenant Info +// 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 { @@ -37,11 +37,13 @@ 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, - }} + }, + } var response api_payloads.TenantUserPayload if err := a.PostAndValidate(ctx, api_endpoints.CreateTenantUserPath(tenantID), request, &response); err != nil { return nil, err diff --git a/kentikapi/internal/api_resources/my_kentik_portal_test.go b/kentikapi/internal/resources/my_kentik_portal_test.go similarity index 86% rename from kentikapi/internal/api_resources/my_kentik_portal_test.go rename to kentikapi/internal/resources/my_kentik_portal_test.go index 2eab99a5..d21fc195 100644 --- a/kentikapi/internal/api_resources/my_kentik_portal_test.go +++ b/kentikapi/internal/resources/my_kentik_portal_test.go @@ -1,4 +1,4 @@ -package api_resources_test +package resources_test import ( "context" @@ -6,7 +6,7 @@ import ( "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/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,7 @@ import ( ) func TestTenantsList(t *testing.T) { - //arrange + // arrange getAllResponse := ` [ { @@ -84,20 +84,19 @@ func TestTenantsList(t *testing.T) { } transport := &api_connection.StubTransport{ResponseBody: getAllResponse} - myKentikPortalAPI := api_resources.NewMyKentikPortalAPI(transport) + 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) { @@ -151,16 +150,16 @@ func TestGetTenantInfo(t *testing.T) { } transport := &api_connection.StubTransport{ResponseBody: getTenantInfoResponse} - myKentikPortalAPI := api_resources.NewMyKentikPortalAPI(transport) + 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) } @@ -183,14 +182,14 @@ func TestTenantUserCreate(t *testing.T) { } transport := &api_connection.StubTransport{ResponseBody: createTenantUserResponse} - myKentikPortalAPI := api_resources.NewMyKentikPortalAPI(transport) + 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) @@ -204,7 +203,7 @@ func TestTenantUserDelete(t *testing.T) { // arrange deleteResponsePayload := "" transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} - myKentikPortalAPI := api_resources.NewMyKentikPortalAPI(transport) + myKentikPortalAPI := resources.NewMyKentikPortalAPI(transport) // act tenantID := models.ID(478) @@ -215,5 +214,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/api_resources/plans.go b/kentikapi/internal/resources/plans.go similarity index 91% rename from kentikapi/internal/api_resources/plans.go rename to kentikapi/internal/resources/plans.go index 600de1bc..3ecc3406 100644 --- a/kentikapi/internal/api_resources/plans.go +++ b/kentikapi/internal/resources/plans.go @@ -1,4 +1,4 @@ -package api_resources +package resources import ( "context" @@ -13,14 +13,14 @@ type PlansAPI struct { BaseAPI } -// NewPlansAPI is constructor +// NewPlansAPI is constructor. func NewPlansAPI(transport api_connection.Transport) *PlansAPI { return &PlansAPI{ BaseAPI{Transport: transport}, } } -// GetAll plans +// 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 { diff --git a/kentikapi/internal/api_resources/plans_test.go b/kentikapi/internal/resources/plans_test.go similarity index 94% rename from kentikapi/internal/api_resources/plans_test.go rename to kentikapi/internal/resources/plans_test.go index 204a1bad..bc4f4c6f 100644 --- a/kentikapi/internal/api_resources/plans_test.go +++ b/kentikapi/internal/resources/plans_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/resources" "github.com/kentik/community_sdk_golang/kentikapi/models" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -66,7 +66,7 @@ func TestGetAllPlans(t *testing.T) { ] }` transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - plansAPI := api_resources.NewPlansAPI(transport) + plansAPI := resources.NewPlansAPI(transport) // act plans, err := plansAPI.GetAll(context.Background()) diff --git a/kentikapi/internal/api_resources/query.go b/kentikapi/internal/resources/query.go similarity index 95% rename from kentikapi/internal/api_resources/query.go rename to kentikapi/internal/resources/query.go index 14d4327f..67a3e2d4 100644 --- a/kentikapi/internal/api_resources/query.go +++ b/kentikapi/internal/resources/query.go @@ -1,4 +1,4 @@ -package api_resources +package resources import ( "context" @@ -13,14 +13,14 @@ type QueryAPI struct { BaseAPI } -// NewQueryAPI is constructor +// NewQueryAPI is constructor. func NewQueryAPI(transport api_connection.Transport) *QueryAPI { return &QueryAPI{ BaseAPI{Transport: transport}, } } -// SQL query +// SQL query. func (a *QueryAPI) SQL(ctx context.Context, sql string) (models.QuerySQLResult, error) { payload := api_payloads.QuerySQLRequest{Query: sql} @@ -32,7 +32,7 @@ func (a *QueryAPI) SQL(ctx context.Context, sql string) (models.QuerySQLResult, return response.ToQuerySQLResult(), nil } -// Data query +// Data query. func (a *QueryAPI) Data(ctx context.Context, query models.QueryObject) (models.QueryDataResult, error) { payload, err := api_payloads.QueryObjectToPayload(query) if err != nil { @@ -47,7 +47,7 @@ func (a *QueryAPI) Data(ctx context.Context, query models.QueryObject) (models.Q return response.ToQueryDataResult(), nil } -// Chart query +// Chart query. func (a *QueryAPI) Chart(ctx context.Context, query models.QueryObject) (models.QueryChartResult, error) { payload, err := api_payloads.QueryObjectToPayload(query) if err != nil { @@ -62,7 +62,7 @@ func (a *QueryAPI) Chart(ctx context.Context, query models.QueryObject) (models. return response.ToQueryChartResult() } -// URL query +// URL query. func (a *QueryAPI) URL(ctx context.Context, query models.QueryObject) (models.QueryURLResult, error) { payload, err := api_payloads.QueryObjectToPayload(query) if err != nil { diff --git a/kentikapi/internal/api_resources/query_test.go b/kentikapi/internal/resources/query_test.go similarity index 91% rename from kentikapi/internal/api_resources/query_test.go rename to kentikapi/internal/resources/query_test.go index 35406d2c..b57ea376 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" @@ -7,7 +7,7 @@ import ( "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/resources" "github.com/kentik/community_sdk_golang/kentikapi/internal/utils" "github.com/kentik/community_sdk_golang/kentikapi/models" "github.com/stretchr/testify/assert" @@ -48,7 +48,7 @@ func TestQuerySQL(t *testing.T) { ] }` transport := &api_connection.StubTransport{ResponseBody: queryResponsePayload} - queryAPI := api_resources.NewQueryAPI(transport) + queryAPI := resources.NewQueryAPI(transport) // act result, err := queryAPI.SQL(context.TODO(), querySQL) @@ -124,11 +124,19 @@ func TestQueryData(t *testing.T) { ] }` transport := &api_connection.StubTransport{ResponseBody: queryResponsePayload} - queryAPI := api_resources.NewQueryAPI(transport) + 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 +146,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") @@ -203,13 +217,25 @@ func TestQueryChart(t *testing.T) { data := "ImageDataEncodedBase64==" queryResponsePayload := `{"dataUri": "data:image/png;base64,ImageDataEncodedBase64=="}` transport := &api_connection.StubTransport{ResponseBody: queryResponsePayload} - queryAPI := api_resources.NewQueryAPI(transport) + 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 +243,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 +259,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") @@ -324,7 +359,7 @@ func TestQueryURL(t *testing.T) { 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) + 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/api_resources/saved_filters.go b/kentikapi/internal/resources/saved_filters.go similarity index 98% rename from kentikapi/internal/api_resources/saved_filters.go rename to kentikapi/internal/resources/saved_filters.go index 4e6842ab..f1bb8ef9 100644 --- a/kentikapi/internal/api_resources/saved_filters.go +++ b/kentikapi/internal/resources/saved_filters.go @@ -1,4 +1,4 @@ -package api_resources +package resources import ( "context" diff --git a/kentikapi/internal/api_resources/saved_filters_test.go b/kentikapi/internal/resources/saved_filters_test.go similarity index 89% rename from kentikapi/internal/api_resources/saved_filters_test.go rename to kentikapi/internal/resources/saved_filters_test.go index e230df96..fb600146 100644 --- a/kentikapi/internal/api_resources/saved_filters_test.go +++ b/kentikapi/internal/resources/saved_filters_test.go @@ -1,4 +1,4 @@ -package api_resources_test +package resources_test import ( "context" @@ -6,7 +6,7 @@ import ( "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/resources" "github.com/kentik/community_sdk_golang/kentikapi/models" "github.com/stretchr/testify/assert" ) @@ -125,7 +125,7 @@ func TestSavedFiltersList(t *testing.T) { } transport := &api_connection.StubTransport{ResponseBody: getAllresponsePayload} - savedFiltersAPI := api_resources.NewSavedFiltersAPI(transport) + savedFiltersAPI := resources.NewSavedFiltersAPI(transport) savedFilters, err := savedFiltersAPI.GetAll(context.Background()) @@ -189,7 +189,7 @@ func TestGetSavedFilterInfo(t *testing.T) { } transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - savedFiltersAPI := api_resources.NewSavedFiltersAPI(transport) + savedFiltersAPI := resources.NewSavedFiltersAPI(transport) savedFilter, err := savedFiltersAPI.Get(context.Background(), 8275) @@ -250,12 +250,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) + savedFiltersAPI := resources.NewSavedFiltersAPI(transport) newSavedFilter := models.SavedFilter{ FilterName: "test_filter1", @@ -309,12 +311,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) + savedFiltersAPI := resources.NewSavedFiltersAPI(transport) filterID := 8153 toUpdate := models.SavedFilter{ @@ -350,7 +354,7 @@ func TestDeleteSavedFilter(t *testing.T) { deleteResponsePayload := "" transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} - savedFiltersAPI := api_resources.NewSavedFiltersAPI(transport) + savedFiltersAPI := resources.NewSavedFiltersAPI(transport) filterID := 8153 err := savedFiltersAPI.Detete(context.Background(), filterID) diff --git a/kentikapi/internal/api_resources/sites.go b/kentikapi/internal/resources/sites.go similarity index 84% rename from kentikapi/internal/api_resources/sites.go rename to kentikapi/internal/resources/sites.go index 431e1375..a88fdae3 100644 --- a/kentikapi/internal/api_resources/sites.go +++ b/kentikapi/internal/resources/sites.go @@ -1,4 +1,4 @@ -package api_resources +package resources import ( "context" @@ -13,14 +13,14 @@ type SitesAPI struct { BaseAPI } -// NewSitesAPI is constructor +// NewSitesAPI is constructor. func NewSitesAPI(transport api_connection.Transport) *SitesAPI { return &SitesAPI{ BaseAPI{Transport: transport}, } } -// GetAll sites +// 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 { @@ -30,7 +30,7 @@ func (a *SitesAPI) GetAll(ctx context.Context) ([]models.Site, error) { return response.ToSites() } -// Get site with given ID +// 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 { @@ -41,7 +41,7 @@ func (a *SitesAPI) Get(ctx context.Context, id models.ID) (*models.Site, error) return &site, err } -// Create new site +// 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 { @@ -50,7 +50,7 @@ func (a *SitesAPI) Create(ctx context.Context, site models.Site) (*models.Site, request := api_payloads.CreateSiteRequest{Payload: payload} var response api_payloads.CreateSiteResponse - if err := a.PostAndValidate(ctx, api_endpoints.CreateSite(), request, &response); err != nil { + if err = a.PostAndValidate(ctx, api_endpoints.CreateSite(), request, &response); err != nil { return nil, err } @@ -58,7 +58,7 @@ func (a *SitesAPI) Create(ctx context.Context, site models.Site) (*models.Site, return &result, err } -// Update site +// Update site. func (a *SitesAPI) Update(ctx context.Context, site models.Site) (*models.Site, error) { payload, err := api_payloads.SiteToPayload(site) if err != nil { @@ -67,7 +67,7 @@ func (a *SitesAPI) Update(ctx context.Context, site models.Site) (*models.Site, 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 { + if err = a.UpdateAndValidate(ctx, api_endpoints.UpdateSite(site.ID), request, &response); err != nil { return nil, err } @@ -75,7 +75,7 @@ func (a *SitesAPI) Update(ctx context.Context, site models.Site) (*models.Site, return &result, err } -// Delete site +// 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 diff --git a/kentikapi/internal/api_resources/sites_test.go b/kentikapi/internal/resources/sites_test.go similarity index 93% rename from kentikapi/internal/api_resources/sites_test.go rename to kentikapi/internal/resources/sites_test.go index fb52bacf..a4797b24 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/resources" "github.com/kentik/community_sdk_golang/kentikapi/internal/utils" "github.com/kentik/community_sdk_golang/kentikapi/models" "github.com/stretchr/testify/assert" @@ -25,7 +25,7 @@ func TestGetSite(t *testing.T) { } }` transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - sitesAPI := api_resources.NewSitesAPI(transport) + sitesAPI := resources.NewSitesAPI(transport) siteID := models.ID(42) // act @@ -75,7 +75,7 @@ func TestGetAllSites(t *testing.T) { ] }` transport := &api_connection.StubTransport{ResponseBody: getResponsePayload} - sitesAPI := api_resources.NewSitesAPI(transport) + sitesAPI := resources.NewSitesAPI(transport) // act sites, err := sitesAPI.GetAll(context.Background()) @@ -125,7 +125,7 @@ func TestCreateSite(t *testing.T) { } }` transport := &api_connection.StubTransport{ResponseBody: createResponsePayload} - sitesAPI := api_resources.NewSitesAPI(transport) + sitesAPI := resources.NewSitesAPI(transport) // act site := models.NewSite("apitest-site-1") @@ -165,7 +165,7 @@ func TestUpdateSite(t *testing.T) { } }` transport := &api_connection.StubTransport{ResponseBody: updateResponsePayload} - sitesAPI := api_resources.NewSitesAPI(transport) + sitesAPI := resources.NewSitesAPI(transport) // act siteID := models.ID(42) @@ -196,7 +196,7 @@ func TestDeleteSite(t *testing.T) { // arrange deleteResponsePayload := "" // deleting site responds with empty body transport := &api_connection.StubTransport{ResponseBody: deleteResponsePayload} - sitesAPI := api_resources.NewSitesAPI(transport) + 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 98% rename from kentikapi/internal/api_resources/tags.go rename to kentikapi/internal/resources/tags.go index a8560d5a..9878face 100644 --- a/kentikapi/internal/api_resources/tags.go +++ b/kentikapi/internal/resources/tags.go @@ -1,4 +1,5 @@ -package api_resources +//nolint:dupl +package resources import ( "context" diff --git a/kentikapi/internal/api_resources/users.go b/kentikapi/internal/resources/users.go similarity index 98% rename from kentikapi/internal/api_resources/users.go rename to kentikapi/internal/resources/users.go index bab743e3..2fae0eb6 100644 --- a/kentikapi/internal/api_resources/users.go +++ b/kentikapi/internal/resources/users.go @@ -1,4 +1,5 @@ -package api_resources +//nolint:dupl +package resources import ( "context" 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..3c01706d 100644 --- a/kentikapi/internal/utils/convert_test.go +++ b/kentikapi/internal/utils/convert_test.go @@ -26,7 +26,7 @@ func TestConvertOrNoneReturnsValue(t *testing.T) { func TestConvertOrNoneReturnsNil(t *testing.T) { // given - var input *string = nil + var input *string var output *int // when 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..0f02da64 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,gocyclo 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..22cd2100 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 + // Note: for DeviceBGPType = DeviceBGPTypeDevice, either DeviceBGPNeighborIP or DeviceBGPNeighborIPv6 is required + DeviceBGPType *DeviceBGPType 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..28bc2347 100644 --- a/kentikapi/tags_integration_test.go +++ b/kentikapi/tags_integration_test.go @@ -81,6 +81,7 @@ func TestClient_GetAllTags(t *testing.T) { }, }, } + //nolint:dupl for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // arrange @@ -361,6 +362,7 @@ func TestClient_CreateTag(t *testing.T) { } } +//nolint:dupl func TestClient_UpdateTag(t *testing.T) { tests := []struct { name string @@ -491,6 +493,7 @@ func TestClient_UpdateTag(t *testing.T) { }, }, } + //nolint:dupl for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // arrange @@ -614,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 edc465a8..e8d11733 100644 --- a/kentikapi/users_integration_test.go +++ b/kentikapi/users_integration_test.go @@ -9,13 +9,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" @@ -158,6 +158,7 @@ func TestClient_GetAllUsers(t *testing.T) { }}, }, } + //nolint:dupl for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // arrange @@ -196,34 +197,34 @@ func TestClient_GetAllUsers(t *testing.T) { func TestClient_GetUser(t *testing.T) { 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 +260,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", @@ -338,7 +339,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)) } @@ -355,7 +356,7 @@ func TestClient_CreateUser(t *testing.T) { 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 +380,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 +421,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 +458,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 +487,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", @@ -560,13 +561,12 @@ 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) - }) } } @@ -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