Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
wecc committed Jan 26, 2017
0 parents commit a19abc7
Show file tree
Hide file tree
Showing 12 changed files with 968 additions and 0 deletions.
24 changes: 24 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so

# Folders
_obj
_test

# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out

*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*

_testmain.go

*.exe
*.test
*.prof
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2017 GleSYS Internet Services AB

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
72 changes: 72 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# glesys-go

This is the official client library for interacting with the
[GleSYS API](https://github.com/GleSYS/API/).

## Requirements

- Go 1.7 or higher (relies on [context](https://golang.org/pkg/context/))

## Getting Started

#### Installation

```shell
go get github.com/glesys/glesys-go
```

#### Authentication

To use the glesys-go library you need a GleSYS Cloud account and a valid API
key. You can sign up for an account at https://glesys.com/signup. After signing
up visit https://customer.glesys.com to create an API key for your Project.

#### Set up a Client

```go
client := glesys.NewClient("CL12345", "your-api-key")
```

#### Create a Server

```go
// Create a Server
server, err := client.Servers.Create(context.Background(), glesys.CreateServerParams{Password: "..."}.WithDefaults())
```

#### List all Servers

```go
// List all Servers
servers, err := client.Servers.List(context.Background())
```

#### Context

glesys-go uses Go's [context](https://golang.org/pkg/context) library to handle
timeouts and deadlines. All functions making HTTP requests requires a `context`
argument.

### Documentation

Full documentation is available at
https://godoc.org/github.com/glesys/glesys-go.

## Contribute

#### We love Pull Requests ♥

1. Fork the repo.
2. Make sure to run the tests to verify that you're starting with a clean slate.
3. Add a test for your change, make sure it fails. Refactoring existing code or
improving documenation does not require new tests.
4. Make the changes and ensure the test pass.
5. Commit your changes, push to your fork and submit a Pull Request.

#### Syntax

Please use the formatting provided by [gofmt](https://golang.org/cmd/gofmt).

## License

The contents of this repository are distributed under the MIT license, see [LICENSE](LICENSE).
144 changes: 144 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
package glesys

import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
)

type httpClientInterface interface {
Do(*http.Request) (*http.Response, error)
}

type clientInterface interface {
get(ctx context.Context, path string, v interface{}) error
post(ctx context.Context, path string, v interface{}, params interface{}) error
}

// Client is used to interact with the GleSYS API
type Client struct {
apiKey string
baseURL *url.URL
httpClient httpClientInterface
project string

IPs *IPService
Servers *ServerService
Version string
}

// NewClient creates a new Client for interacting with the GleSYS API. This is
// the main entrypoint for API interactions.
func NewClient(project, apiKey string) *Client {
baseURL, _ := url.Parse("https://api.glesys.com")

c := &Client{
apiKey: apiKey,
baseURL: baseURL,
httpClient: http.DefaultClient,
project: project,
Version: "1.0.0",
}

c.IPs = &IPService{client: c}
c.Servers = &ServerService{client: c}

return c
}

func (c *Client) get(ctx context.Context, path string, v interface{}) error {
request, err := c.newRequest(ctx, "GET", path, nil)
if err != nil {
return err
}
return c.do(request, v)
}

func (c *Client) post(ctx context.Context, path string, v interface{}, params interface{}) error {
request, err := c.newRequest(ctx, "POST", path, params)
if err != nil {
return err
}
return c.do(request, v)
}

func (c *Client) newRequest(ctx context.Context, method, path string, params interface{}) (*http.Request, error) {
u, err := url.Parse(path)
if err != nil {
return nil, err
}

if c.baseURL != nil {
u = c.baseURL.ResolveReference(u)
}

buffer := new(bytes.Buffer)

if params != nil {
err = json.NewEncoder(buffer).Encode(params)
if err != nil {
return nil, err
}
}

request, err := http.NewRequest(method, u.String(), buffer)
if err != nil {
return nil, err
}

request = request.WithContext(ctx)
request.Header.Set("Content-Type", "application/json")
request.Header.Set("User-Agent", fmt.Sprintf("glesys-go/%s", c.Version))
request.SetBasicAuth(c.project, c.apiKey)

return request, nil
}

func (c *Client) do(request *http.Request, v interface{}) error {
response, err := c.httpClient.Do(request)
if err != nil {
return err
}

if response.StatusCode != http.StatusOK {
return c.handleResponseError(response)
}

return c.parseResponseBody(response, v)
}

func (c *Client) handleResponseError(response *http.Response) error {
data := struct {
Response struct {
Status struct {
Text string `json:"text"`
} `json:"status"`
} `json:"response"`
}{}

err := c.parseResponseBody(response, &data)
if err != nil {
return err
}

return fmt.Errorf("Request failed with HTTP error: %v (%v)", response.StatusCode, strings.TrimSpace(data.Response.Status.Text))
}

func (c *Client) parseResponseBody(response *http.Response, v interface{}) error {
if v == nil {
return nil
}

defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}

return json.Unmarshal(body, v)
}
113 changes: 113 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
package glesys

import (
"bytes"
"context"
"encoding/json"
"io/ioutil"
"net/http"
"testing"

"github.com/stretchr/testify/assert"
)

type mockHTTPClient struct {
body string
lastRequest *http.Request
statusCode int
}

func (c *mockHTTPClient) Do(request *http.Request) (*http.Response, error) {
response := http.Response{
StatusCode: c.statusCode,
Body: ioutil.NopCloser(bytes.NewBufferString(c.body)),
}
c.lastRequest = request
return &response, nil
}

func TestRequestHasCorrectHeaders(t *testing.T) {
client := NewClient("project-id", "api-key")

request, err := client.newRequest(context.Background(), "GET", "/", nil)
assert.NoError(t, err)

assert.Equal(t, "application/json", request.Header.Get("Content-Type"), "header Content-Type is correct")
assert.Equal(t, "glesys-go/1.0.0", request.Header.Get("User-Agent"), "header User-Agent is correct")

assert.NotEmpty(t, request.Header.Get("Authorization"), "header Authorization is not empty")
}

func TestGetResponseErrorMessage(t *testing.T) {
client := NewClient("project-id", "api-key")

json := `{ "response": {"status": { "code": 400, "text": "Unauthorized" } } }`
response := http.Response{
Body: ioutil.NopCloser(bytes.NewBufferString(json)),
StatusCode: 400,
}
err := client.handleResponseError(&response)
assert.Equal(t, "Request failed with HTTP error: 400 (Unauthorized)", err.Error(), "error message is correct")
}

func TestDoDoesNotReturnErrorIfStatusIs200(t *testing.T) {
payload := `{ "response": { "hello": "world" } }`
client := Client{httpClient: &mockHTTPClient{body: payload, statusCode: 200}}

request, _ := client.newRequest(context.Background(), "GET", "/", nil)
err := client.do(request, nil)

assert.NoError(t, err, "do does not return an error")
}

func TestDoReturnsErrorIfStatusIsNot200(t *testing.T) {
payload := `{ "response": { "foo": "bar" } }`
client := Client{httpClient: &mockHTTPClient{body: payload, statusCode: 500}}

request, _ := client.newRequest(context.Background(), "GET", "/", nil)
err := client.do(request, nil)

assert.Error(t, err, "do returns an error")
}

func TestDoDecodesTheJsonResponseIntoAStruct(t *testing.T) {
payload := `{ "response": { "message": "Hello World" } }`
client := Client{httpClient: &mockHTTPClient{body: payload, statusCode: 200}}

request, _ := client.newRequest(context.Background(), "GET", "/", nil)

data := struct {
Response struct {
Message string
}
}{}
err := client.do(request, &data)

assert.NoError(t, err)
assert.Equal(t, "Hello World", data.Response.Message, "JSON was parsed correctly")
}

func TestGet(t *testing.T) {
payload := `{ "response": { "message": "Hello World" } }`
mockClient := mockHTTPClient{body: payload, statusCode: 200}
client := Client{httpClient: &mockClient}

data := struct{}{}
client.get(context.Background(), "/foo", data)

assert.Equal(t, "GET", mockClient.lastRequest.Method, "method used is correct")
}

func TestPost(t *testing.T) {
payload := `{ "response": { "message": "Hello World" } }`
mockClient := mockHTTPClient{body: payload, statusCode: 200}
client := Client{httpClient: &mockClient}

client.post(context.Background(), "/foo", nil, struct{ Foo string }{Foo: "bar"})

params := struct{ Foo string }{}
json.NewDecoder(mockClient.lastRequest.Body).Decode(&params)

assert.Equal(t, "POST", mockClient.lastRequest.Method, "method used is correct")
assert.Equal(t, "bar", params.Foo, "params are correct")
}
Loading

0 comments on commit a19abc7

Please sign in to comment.