Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Do not merge]Go Component - FetchAndPersist #186

Open
wants to merge 46 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
4e6fd2c
Go - fetch and persist implementation
ashiqueps Jul 2, 2024
c4c10d2
Fixed the issue with license details not showing up on the warning sc…
ashiqueps Jul 3, 2024
44d0ba8
added some fixes
nikhil2611 Jul 3, 2024
bf4089d
Merge branch 'CHEF-2618-go-implementation-chef-licensing' of github.c…
ashiqueps Jul 3, 2024
30db893
Updated the typo
ashiqueps Jul 3, 2024
d3ec161
Fixed the final error handling
ashiqueps Jul 3, 2024
d7d2911
added log to print license-key
nikhil2611 Jul 3, 2024
de76f9a
Updated the fmt.println to log.println
ashiqueps Jul 3, 2024
11954b2
reverted back the print log
nikhil2611 Jul 3, 2024
81a1490
Fixed the styling issues on the interactions
ashiqueps Jul 4, 2024
e90df28
Merge branch 'CHEF-2618-go-implementation-chef-licensing' of github.c…
ashiqueps Jul 4, 2024
3fb44dc
Updated the interactions.yml file
ashiqueps Jul 5, 2024
566699f
added the logic to accept the --chef-license-key flag and arguments
nikhil2611 Jul 8, 2024
5fd1e6d
Added unit tests
ashiqueps Jul 9, 2024
e441486
Merge branch 'CHEF-2618-go-implementation-chef-licensing' of github.c…
ashiqueps Jul 9, 2024
cdf0e2d
Removed exception causing test case
ashiqueps Jul 10, 2024
9fbe422
added the logic to remove --chef-license-key flag from os.Args
nikhil2611 Jul 10, 2024
f60b5fb
Code style changes
ashiqueps Jul 10, 2024
c400c53
Merge branch 'CHEF-2618-go-implementation-chef-licensing' of github.c…
ashiqueps Jul 10, 2024
5b49295
Updated the verify pipelines commands
ashiqueps Jul 10, 2024
172b68b
fixed the typo
ashiqueps Jul 10, 2024
47b55df
Updated the commands
ashiqueps Jul 10, 2024
1294d6b
Fixed the file_fetcher_test
ashiqueps Jul 10, 2024
954346e
Added logs to debug the test case
ashiqueps Jul 10, 2024
7ea3a1d
Added more logs
ashiqueps Jul 10, 2024
d009fe9
Removed the logs added for testing
ashiqueps Jul 11, 2024
d1adf88
Updated the go version to 1.21.5
ashiqueps Jul 11, 2024
eaf073d
Added the TTY conditions
ashiqueps Jul 11, 2024
94e4b50
Hard enforcement fix: Adding the same type of license
nikhil2611 Jul 15, 2024
d071c23
Updated the spinner
ashiqueps Jul 15, 2024
6968351
Merge branch 'CHEF-2618-go-implementation-chef-licensing' of github.c…
ashiqueps Jul 15, 2024
6157f7b
Merge branch 'main' of github.com:chef/chef-licensing into CHEF-2618-…
ashiqueps Jul 15, 2024
b0db8b0
TTY related fixes
ashiqueps Jul 15, 2024
fd50d79
Codereview comments
ashiqueps Jul 17, 2024
737ab7f
More code review comments addressed
ashiqueps Jul 17, 2024
938375b
Merge branch 'main' of github.com:chef/chef-licensing into CHEF-2618-…
ashiqueps Jul 28, 2024
ab03ac2
On prem fetch and persist implementation
ashiqueps Jul 31, 2024
482a4a5
Logs for debugging the issue on buildkite
ashiqueps Aug 1, 2024
deb06b9
Removed the failing test case
ashiqueps Aug 1, 2024
b4a9496
Debugging
ashiqueps Aug 1, 2024
237fc7c
Debugging
ashiqueps Aug 1, 2024
1acf0a8
debugging again
ashiqueps Aug 1, 2024
e68815d
printing the content for testing
ashiqueps Aug 1, 2024
e3f6419
Fixes for the test cases
ashiqueps Aug 1, 2024
eb208c2
Hanlded the software not entitled error
ashiqueps Aug 6, 2024
f37ac5c
Removed the unwanted test file
ashiqueps Aug 7, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .expeditor/run_go_tests.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#!/bin/bash

go get .
go mod tidy

go test -v ./...
11 changes: 11 additions & 0 deletions .expeditor/verify.pipeline.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,14 @@ steps:
host_os: windows
shell: ["powershell", "-Command"]
image: rubydistros/windows-2019:3.1

- label: run-go-tests-1.22.4-ubuntu
commands:
- cd /workdir/components/go
# - go get .
- go mod tidy
- go test ./...
expeditor:
executor:
docker:
image: golang:1.22-bullseye
13 changes: 13 additions & 0 deletions components/go/example/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package main

import (
"fmt"

cheflicensing "github.com/chef/chef-licensing/components/go/pkg"
"github.com/chef/chef-licensing/components/go/pkg/config"
)

func main() {
config.SetConfig("Workstation", "x6f3bc76-a94f-4b6c-bc97-4b7ed2b045c0", "https://licensing-acceptance.chef.co/License", "chef")
fmt.Println(cheflicensing.FetchAndPersist())
}
42 changes: 42 additions & 0 deletions components/go/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
module github.com/chef/chef-licensing/components/go

go 1.21.5

require (
github.com/cqroot/prompt v0.9.3
github.com/gookit/color v1.5.4
// github.com/progress-platform-services/chef-platform-license-management v0.3.1
github.com/theckman/yacspin v0.13.12
gopkg.in/yaml.v2 v2.4.0
// github.com/progress-platform-services/chef-platform-license-management/public/client/license-management
)

require (
github.com/atotto/clipboard v0.1.4 // indirect
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/charmbracelet/bubbles v0.16.1 // indirect
github.com/charmbracelet/bubbletea v0.24.2 // indirect
github.com/charmbracelet/lipgloss v0.9.1 // indirect
github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 // indirect
github.com/cqroot/multichoose v0.1.1 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/fatih/color v1.13.0 // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-localereader v0.0.1 // indirect
github.com/mattn/go-runewidth v0.0.15 // indirect
github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/muesli/reflow v0.3.0 // indirect
github.com/muesli/termenv v0.15.2 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/stretchr/testify v1.9.0 // indirect
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 // indirect
golang.org/x/sync v0.7.0 // indirect
golang.org/x/sys v0.22.0 // indirect
golang.org/x/term v0.22.0
golang.org/x/text v0.16.0 // indirect
)
79 changes: 79 additions & 0 deletions components/go/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
github.com/charmbracelet/bubbles v0.16.1 h1:6uzpAAaT9ZqKssntbvZMlksWHruQLNxg49H5WdeuYSY=
github.com/charmbracelet/bubbles v0.16.1/go.mod h1:2QCp9LFlEsBQMvIYERr7Ww2H2bA7xen1idUDIzm/+Xc=
github.com/charmbracelet/bubbletea v0.24.2 h1:uaQIKx9Ai6Gdh5zpTbGiWpytMU+CfsPp06RaW2cx/SY=
github.com/charmbracelet/bubbletea v0.24.2/go.mod h1:XdrNrV4J8GiyshTtx3DNuYkR1FDaJmO3l2nejekbsgg=
github.com/charmbracelet/lipgloss v0.9.1 h1:PNyd3jvaJbg4jRHKWXnCj1akQm4rh8dbEzN1p/u1KWg=
github.com/charmbracelet/lipgloss v0.9.1/go.mod h1:1mPmG4cxScwUQALAAnacHaigiiHB9Pmr+v1VEawJl6I=
github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 h1:q2hJAaP1k2wIvVRd/hEHD7lacgqrCPS+k8g1MndzfWY=
github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81/go.mod h1:YynlIjWYF8myEu6sdkwKIvGQq+cOckRm6So2avqoYAk=
github.com/cqroot/multichoose v0.1.1 h1:diGuKYKea9ePOTwUyUDor9zKRqKFWXGkYGqUa9+firU=
github.com/cqroot/multichoose v0.1.1/go.mod h1:BJzIGqbQZNADPDuA3IzhmTMpRc2F3fZKysMRYP+Ydw8=
github.com/cqroot/prompt v0.9.3 h1:00Sjiasl1QL7ttEphJ+1xAl0fKQi+7s2F3aY0x7wnz4=
github.com/cqroot/prompt v0.9.3/go.mod h1:NZvCTeuvR9ew9Hkk7xlrZ9xdVH4AmkO9R0eeBkzOHXQ=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w=
github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0=
github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b h1:1XF24mVaiu7u+CFywTdcDo2ie1pzzhwjt6RHqzpMU34=
github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b/go.mod h1:fQuZ0gauxyBcmsdE3ZT4NasjaRdxmbCS0jRHsrWu3Ho=
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=
github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=
github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo=
github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/theckman/yacspin v0.13.12 h1:CdZ57+n0U6JMuh2xqjnjRq5Haj6v1ner2djtLQRzJr4=
github.com/theckman/yacspin v0.13.12/go.mod h1:Rd2+oG2LmQi5f3zC3yeZAOl245z8QOvrH4OPOJNZxLg=
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 h1:QldyIu/L63oPpyvQmHgvgickp1Yw510KJOqX7H24mg8=
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778/go.mod h1:2MuV+tbUrU1zIOPMxZ5EncGwgmMJsa+9ucAQZXxsObs=
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.22.0 h1:BbsgPEJULsl2fV/AT3v15Mjva5yXKQDyKf+TbDz7QJk=
golang.org/x/term v0.22.0/go.mod h1:F3qCibpT5AMpCRfhfT53vVJwhLtIVHhB9XDjfFvnMI4=
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
139 changes: 139 additions & 0 deletions components/go/pkg/api/api_client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
package api

import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"sync"

config "github.com/chef/chef-licensing/components/go/pkg/config"
// licenseclient "github.com/progress-platform-services/chef-platform-license-management/public/client/license-management/license"
)

const (
CLIENT_VERSION = "v1"
)

type APIClient struct {
URL string
HTTPClient *http.Client
Headers map[string]string
}

var (
apiClient *APIClient
once sync.Once
)

ashiqueps marked this conversation as resolved.
Show resolved Hide resolved
func (c *APIClient) BaseURL() string {
baseUrl, err := url.Parse(fmt.Sprintf("%s/%s/", c.URL, CLIENT_VERSION))
if err != nil {
log.Fatal("Error parsing the provided URL: ", err)
}
return baseUrl.String()
}

// func NewAPIClient() licenseclient.LicenseClient {
// cfg := config.GetConfig()
// conf := pconfig.DefaultHttpConfig(cfg.LicenseServerURL)
// logger, err := plogger.NewLogger(plogger.LoggerConfig{LogLevel: "debug", LogToStdout: true})
// fmt.Println("Loggflaslfjalskfjlaksfjlkj")
// logger.Warn("Test log")
// if err != nil {
// log.Fatal("Unable to create a logger", err)
// }
// agent, err := pagent.NewAgent(conf, pagent.BasicClient, pauthtype.NoAuth{}, pcache.NewLocalCache(time.Second*60, time.Second*60), logger)
// if err != nil {
// log.Fatal("Unable to create the api client ", err)
// }
// return licenseclient.NewLicenseClient(conf, agent, nil, false, nil, nil, logger)
// }

func NewClient() *APIClient {
cfg := config.GetConfig()

apiClient = &APIClient{
URL: cfg.LicenseServerURL,
HTTPClient: &http.Client{},
Headers: map[string]string{
"Content-Type": "application/json",
},
}
return apiClient
}

func GetClient() *APIClient {
ashiqueps marked this conversation as resolved.
Show resolved Hide resolved
once.Do(func() {
apiClient = NewClient()
})

return apiClient
}

func (c *APIClient) SetHeader(key, value string) {
c.Headers[key] = value
}

func (c *APIClient) doGETRequest(endpoint string, queryParams map[string]string) (*http.Response, error) {
urlObj, err := url.Parse(endpoint)
if err != nil {
return nil, err
}

if queryParams != nil {
q := urlObj.Query()
for key, value := range queryParams {
q.Add(key, value)
}
urlObj.RawQuery = q.Encode()
}
return c.doRequest("GET", urlObj.String(), nil)
}

func (c *APIClient) doPOSTRequest(endpoint string, body interface{}) (*http.Response, error) {
var reqBody io.Reader
var err error

if body != nil {
reqBody, err = c.encodeJSON(body)
if err != nil {
return nil, err
}
}
return c.doRequest("POST", endpoint, reqBody)
}

func (c *APIClient) doRequest(method, endpoint string, body io.Reader) (*http.Response, error) {
url := c.BaseURL() + endpoint
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}

for key, value := range c.Headers {
req.Header.Set(key, value)
}
return c.HTTPClient.Do(req)
}

func (c *APIClient) decodeJSON(resp *http.Response, v interface{}) {
defer resp.Body.Close()
err := json.NewDecoder(resp.Body).Decode(v)
if err != nil {
log.Fatal("Failed to parse the response from the server:", err)
}
}

func (c *APIClient) encodeJSON(v interface{}) (io.Reader, error) {
buf := new(bytes.Buffer)
err := json.NewEncoder(buf).Encode(v)
if err != nil {
return nil, err
}

return buf, nil
}
74 changes: 74 additions & 0 deletions components/go/pkg/api/api_client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package api_test

import (
"net/http"
"net/http/httptest"
"testing"

"github.com/chef/chef-licensing/components/go/pkg/api"
"github.com/chef/chef-licensing/components/go/pkg/config"
)

func TestNewClient(t *testing.T) {
setConfig()

client := api.NewClient()
if client.URL != "https://testing.license.chef.io" {
t.Errorf("expected BaseURL to be %s, got %s", "https://testing.license.chef.io", client.URL)
}
if client.BaseURL() != "https://testing.license.chef.io/v1/" {
t.Errorf("expected BaseURL to be %s, got %s", "https://testing.license.chef.io/v1/", client.BaseURL())
}
if client.HTTPClient == nil {
t.Error("expected HTTPClient to be initialized, got nil")
}
_, ok := interface{}(client.HTTPClient).(*http.Client)
if !ok {
t.Error("expected HTTPClient to be of type *http.Client")
}
}

func TestGetClient(t *testing.T) {
setConfig()

client1 := api.GetClient()
client2 := api.GetClient()

if client1 != client2 {
t.Error("client created multiple times")
}
}

func TestSetHeader(t *testing.T) {
setConfig()
client := api.GetClient()
client.SetHeader("testkey", "testval")
if client.Headers["testkey"] != "testval" {
t.Errorf("expected to set the headers %s:%s, but failed: %v", "testkey", "testval", client.Headers)
}
}

func MockAPIResponse(mockResponse string, status int) *httptest.Server {
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(status)
w.Write([]byte(mockResponse))
}))
setConfig(mockServer.URL)

return mockServer
}

func setConfig(urls ...string) {
var url string
if len(urls) > 0 {
url = urls[0]
} else {
url = "https://testing.license.chef.io"
}
config.NewConfig(&config.LicenseConfig{
ProductName: "Workstation",
EntitlementID: "workstation-1234",
LicenseServerURL: url,
ExecutableName: "test",
})
}
Loading