Skip to content

Commit

Permalink
Modify client package name and update examples (#144)
Browse files Browse the repository at this point in the history
Modify client package name and update examples (#144)
---------

Co-authored-by: Dean Oren <deangili.oren@mail.schwarz>
  • Loading branch information
do87 and Dean Oren committed Mar 23, 2023
1 parent b091ae0 commit 2c68eeb
Show file tree
Hide file tree
Showing 15 changed files with 163 additions and 113 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ TEST?=$$(go list ./... | grep -v -E 'services|vendor|config')

test:
@GOPRIVATE=dev.azure.com go test $(TEST) || exit 1
@echo $(TEST) | xargs -t -n4 go test $(TESTARGS) -timeout=30s -parallel=4
@echo $(TEST) | xargs -t -n4 go test $(TESTARGS) -timeout=30s -parallel=1

coverage:
@go test ./... -coverprofile cover.out
Expand Down
96 changes: 53 additions & 43 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,75 +2,85 @@

[![Go Report Card](https://goreportcard.com/badge/github.com/SchwarzIT/community-stackit-go-client)](https://goreportcard.com/report/github.com/SchwarzIT/community-stackit-go-client) [![Unit Tests](https://github.com/SchwarzIT/community-stackit-go-client/actions/workflows/tests.yml/badge.svg)](https://github.com/SchwarzIT/community-stackit-go-client/actions/workflows/tests.yml) [![Coverage Status](https://coveralls.io/repos/github/SchwarzIT/community-stackit-go-client/badge.svg?branch=main)](https://coveralls.io/github/SchwarzIT/community-stackit-go-client?branch=main) [![GoDoc reference](https://img.shields.io/badge/godoc-reference-blue.svg)](https://pkg.go.dev/github.com/SchwarzIT/community-stackit-go-client) [![License](https://img.shields.io/badge/License-Apache_2.0-lightgray.svg)](https://opensource.org/licenses/Apache-2.0)

<br />
This is a Go client designed to help developers interact with STACKIT APIs. It is maintained by the STACKIT community within Schwarz IT.

The client is community-supported and not an official STACKIT release, it is maintained by internal Schwarz IT teams integrating with STACKIT
&nbsp;

## Install
## Installation

To install the latest stable release, run:
To install the community-stackit-go-client package, run the following command:

```bash
go get github.com/SchwarzIT/community-stackit-go-client@latest
go get github.com/SchwarzIT/community-stackit-go-client
```

## Usage Example
&nbsp;

In order to use the client, a STACKIT Service Account [must be created](https://api.stackit.schwarz/service-account/openapi.v1.html#operation/post-projects-projectId-service-accounts-v2) and have relevant roles [assigned to it](https://api.stackit.schwarz/membership-service/openapi.v1.html#operation/post-organizations-organizationId-projects-projectId-roles-roleName-service-accounts).<br />
For further assistance, please contact [STACKIT support](https://support.stackit.cloud)
## Usage

```Go
Before you can start using the client, you will need to create a STACKIT Service Account and assign it the appropriate permissions.

Create a file called `example.go`:

```go
package main

import (
"context"
"fmt"
"os"
"context"
"fmt"

client "github.com/SchwarzIT/community-stackit-go-client"
"github.com/SchwarzIT/community-stackit-go-client/pkg/validate"
stackit "github.com/SchwarzIT/community-stackit-go-client"
"github.com/SchwarzIT/community-stackit-go-client/pkg/validate"
)

func main() {
ctx := context.Background()
c, err := client.New(ctx, client.Config{
ServiceAccountEmail: os.Getenv("STACKIT_SERVICE_ACCOUNT_EMAIL"),
ServiceAccountToken: os.Getenv("STACKIT_SERVICE_ACCOUNT_TOKEN"),
})
if err != nil {
panic(err)
}

res, err := c.ElasticSearch.Offerings.GetWithResponse(ctx, "{project-id}")
if aggregatedError := validate.Response(res, err, "JSON200"); aggregatedError != nil {
panic(aggregatedError)
}

fmt.Println("Received the following offerings:")
for _, o := range res.JSON200.Offerings {
fmt.Printf("- %s\n", o.Name)
}
ctx := context.Background()
c := stackit.NewClient(ctx)

res, err := c.ElasticSearch.Offerings.Get(ctx, "my-project-id")
if err = validate.Response(res, err, "JSON200"); err != nil {
panic(err)
}

fmt.Println("Received the following offerings:")
for _, o := range res.JSON200.Offerings {
fmt.Printf("- %s\n", o.Name)
}
}
```

Set the following environment variables:

```bash
export STACKIT_SERVICE_ACCOUNT_EMAIL=email
export STACKIT_SERVICE_ACCOUNT_TOKEN=token

# optional: modify the API environment
# set `STACKIT_ENV` to one of `dev`, `qa` or `prod` (default)
export STACKIT_ENV=prod
```

Then, you can run the example with the following command:

```bash
go run example.go
```

### Further Examples

1. Under [`/examples`](https://github.com/SchwarzIT/community-stackit-go-client/tree/main/examples) directory
2. In our [`terraform-provider-stackit`](https://github.com/SchwarzIT/terraform-provider-stackit)

&nbsp;

<br />
## Contributing

## Working with API environments
If you find a bug or have an idea for a new feature, feel free to submit an issue or pull request!

In order to modify the API environment, set the `Environment` field to one of `dev`, `qa` or `prod`
Please make sure to include tests for any new functionality you add, and to run the existing tests before submitting your changes.

- The `Environment` field is optional
- By default `prod` is being used
&nbsp;

```Go
c, err := client.New(ctx, client.Config{
// ...
Environment: "qa"
})
```
## License

This project is licensed under the Apache-2.0 license - see the LICENSE file for details.
36 changes: 32 additions & 4 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
// All services must be initialized in the `init` method, and the client must be configured
// during initialization

package client
package stackit

import (
"context"
Expand All @@ -21,6 +21,12 @@ import (
waitutil "k8s.io/apimachinery/pkg/util/wait"
)

const (
email = "STACKIT_SERVICE_ACCOUNT_EMAIL"
token = "STACKIT_SERVICE_ACCOUNT_TOKEN"
apienv = "STACKIT_ENV"
)

const (
ClientTimeoutErr = "Client.Timeout exceeded while awaiting headers"
ClientContextDeadlineErr = "context deadline exceeded"
Expand All @@ -43,8 +49,8 @@ type Client struct {
services
}

// New returns a new client
func New(ctx context.Context, cfg Config) (*Client, error) {
// NewClientWithConfig returns a new client
func NewClientWithConfig(ctx context.Context, cfg Config) (*Client, error) {
if err := cfg.Validate(); err != nil {
return nil, err
}
Expand All @@ -61,6 +67,28 @@ func New(ctx context.Context, cfg Config) (*Client, error) {
return c, nil
}

// NewClient returns a new client and
// panics if there's an error
// to avoid panics, use NewClientWithConfig instead
func NewClient(ctx context.Context) *Client {
cfg := Config{}
err := cfg.Validate()
if err != nil {
panic(err)
}

c := &Client{
config: cfg,
ctx: ctx,
RetryTimout: 2 * time.Minute,
RetryWait: 30 * time.Second,
}

c.setHttpClient(c.ctx)
c.initServices()
return c
}

// GetHTTPClient returns the HTTP client
func (c *Client) GetHTTPClient() *http.Client {
return c.client
Expand Down Expand Up @@ -143,7 +171,7 @@ func MockServer() (c *Client, mux *http.ServeMux, teardown func(), err error) {

u, _ := url.Parse(server.URL)

c, err = New(context.Background(), Config{
c, err = NewClientWithConfig(context.Background(), Config{
BaseUrl: u,
ServiceAccountToken: "token",
ServiceAccountEmail: "sa-id",
Expand Down
31 changes: 29 additions & 2 deletions client_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package client
package stackit

import (
"context"
"net/http"
"os"
"reflect"
"testing"
"time"
Expand All @@ -11,6 +12,29 @@ import (
)

func TestNew(t *testing.T) {

eml := os.Getenv(email)
tok := os.Getenv(token)
env := os.Getenv(apienv)

if tok == "" && eml == "" {
os.Setenv(email, "abc")
os.Setenv(token, "efg")
os.Setenv(apienv, "hij")
tc := NewClient(context.Background())
if tc.GetConfig().ServiceAccountEmail != "abc" || tc.GetConfig().ServiceAccountToken != "efg" || tc.GetConfig().Environment != "hij" {
t.Errorf("NewClient config doesn't match")
}
} else {
tc := NewClient(context.Background())
if tc.GetConfig().ServiceAccountEmail != eml || tc.GetConfig().ServiceAccountToken != tok {
t.Errorf("NewClient config doesn't match env")
}
}
os.Setenv(email, "")
os.Setenv(token, "")
os.Setenv(apienv, "")

cfg := Config{
ServiceAccountToken: "token",
ServiceAccountEmail: "sa-id",
Expand All @@ -31,7 +55,7 @@ func TestNew(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := New(tt.args.ctx, tt.args.cfg)
got, err := NewClientWithConfig(tt.args.ctx, tt.args.cfg)
if (err != nil) != tt.wantErr {
t.Errorf("NewAuth() error = %v, wantErr %v", err, tt.wantErr)
return
Expand All @@ -41,6 +65,9 @@ func TestNew(t *testing.T) {
}
})
}
os.Setenv(email, eml)
os.Setenv(token, tok)
os.Setenv(apienv, env)
}

func TestClient_DoWithRetry(t *testing.T) {
Expand Down
20 changes: 17 additions & 3 deletions config.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
// this file holds configuration for both STACKIT and Auth clients
// once the Auth client is retired, related code will be removed

package client
package stackit

import (
"errors"
"net/url"
"os"

"github.com/SchwarzIT/community-stackit-go-client/internal/common"
)
Expand All @@ -20,16 +21,29 @@ type Config struct {

// Validate verifies that the given config is valid
func (c *Config) Validate() error {
if c.ServiceAccountToken == "" {
e := os.Getenv(email)
t := os.Getenv(token)
env := os.Getenv(apienv)

if c.ServiceAccountToken == "" && t == "" {
return errors.New("Service Account Access Token cannot be empty")
}
if c.ServiceAccountToken == "" {
c.ServiceAccountToken = t
}

if c.ServiceAccountEmail == "" {
if c.ServiceAccountEmail == "" && e == "" {
return errors.New("Service Account Email cannot be empty")
}
if c.ServiceAccountEmail == "" {
c.ServiceAccountEmail = e
}

if c.Environment == "" {
c.Environment = string(common.ENV_PROD)
}
if env != "" {
c.Environment = env
}
return nil
}
12 changes: 11 additions & 1 deletion config_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
package client
package stackit

import (
"net/url"
"os"
"testing"
)

func TestConfig_Validate(t *testing.T) {
eml := os.Getenv("STACKIT_SERVICE_ACCOUNT_EMAIL")
tok := os.Getenv("STACKIT_SERVICE_ACCOUNT_TOKEN")
env := os.Getenv("STACKIT_ENV")
os.Setenv("STACKIT_SERVICE_ACCOUNT_EMAIL", "")
os.Setenv("STACKIT_SERVICE_ACCOUNT_TOKEN", "")
os.Setenv("STACKIT_ENV", "")
type fields struct {
BaseUrl *url.URL
Token string
Expand All @@ -32,4 +39,7 @@ func TestConfig_Validate(t *testing.T) {
}
})
}
os.Setenv("STACKIT_SERVICE_ACCOUNT_EMAIL", eml)
os.Setenv("STACKIT_SERVICE_ACCOUNT_TOKEN", tok)
os.Setenv("STACKIT_ENV", env)
}
11 changes: 2 additions & 9 deletions examples/bucket/bucket.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,14 @@ package main
import (
"context"
"fmt"
"os"

client "github.com/SchwarzIT/community-stackit-go-client"
stackit "github.com/SchwarzIT/community-stackit-go-client"
"github.com/SchwarzIT/community-stackit-go-client/pkg/validate"
)

func main() {
ctx := context.Background()
c, err := client.New(ctx, client.Config{
ServiceAccountEmail: os.Getenv("STACKIT_SERVICE_ACCOUNT_EMAIL"),
ServiceAccountToken: os.Getenv("STACKIT_SERVICE_ACCOUNT_TOKEN"),
})
if err != nil {
panic(err)
}
c := stackit.NewClient(ctx)

projectID := "123-456-789"
bucketName := "bucket"
Expand Down
11 changes: 2 additions & 9 deletions examples/costs/costs.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,16 @@ package main
import (
"context"
"fmt"
"os"

client "github.com/SchwarzIT/community-stackit-go-client"
stackit "github.com/SchwarzIT/community-stackit-go-client"
costs "github.com/SchwarzIT/community-stackit-go-client/pkg/services/costs/v2.0"
"github.com/SchwarzIT/community-stackit-go-client/pkg/validate"
"github.com/google/uuid"
)

func main() {
ctx := context.Background()
c, err := client.New(ctx, client.Config{
ServiceAccountEmail: os.Getenv("STACKIT_SERVICE_ACCOUNT_EMAIL"),
ServiceAccountToken: os.Getenv("STACKIT_SERVICE_ACCOUNT_TOKEN"),
})
if err != nil {
panic(err)
}
c := stackit.NewClient(ctx)

params := &costs.GetProjectCostsParams{}
res, err := c.Costs.GetProjectCosts(
Expand Down
Loading

0 comments on commit 2c68eeb

Please sign in to comment.