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

v4-api #3

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ t := &oauth.Transport{
client := teamweek.NewClient(t.Client())

// Get authenticated user's profile information
profile, err := client.Profile()
profile, err := client.GetUserProfile()
```

See the [goauth2 docs][] for complete instructions on using that library.
Expand Down
107 changes: 107 additions & 0 deletions teamweek/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package teamweek

import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
)

const (
libraryVersion = "0.2"
userAgent = "go-teamweek/" + libraryVersion
defaultBaseURL = "https://teamweek.com/api/v4/"
)

var (
ErrInvalidAuth = errors.New("Invalid authorization, check credentials and/or reauthenticate")
ErrForbidden = errors.New("The ressource your are trying to access is beyond the scope of your current user")
ErrNotFound = errors.New("The requested ressource could not be found.")
ErrInternal = errors.New("Teamweek API experienced an internal error. Please try again later.")
)

type Client struct {
client *http.Client
BaseURL *url.URL
UserAgent string
}

func (c *Client) get(url string, dest interface{}) error {
return c.request(url, http.MethodGet, dest, nil)
}

func (c *Client) request(urlStr, method string, dest, body interface{}) error {
rel, err := url.Parse(urlStr)
if err != nil {
return err
}
u := c.BaseURL.ResolveReference(rel)

var req *http.Request
if body != nil {
var buf bytes.Buffer // request are quite small anyway...
if err := json.NewEncoder(&buf).Encode(&body); err != nil {
return err
}
req, err = http.NewRequest(method, u.String(), &buf)
} else {
req, err = http.NewRequest(method, u.String(), nil)
}

if err != nil {
return err
}
req.Header.Add("User-Agent", c.UserAgent)
if body != nil {
req.Header.Add("Content-Type", "application/json")
}

resp, err := c.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if err := handleResponseStatuses(resp); err != nil {
return err
}

if dest != nil {
return json.NewDecoder(resp.Body).Decode(dest)
}
return nil
}

func handleResponseStatuses(resp *http.Response) error {
switch resp.StatusCode {

case http.StatusUnauthorized: // 401
return ErrInvalidAuth

case http.StatusForbidden: // 403
return ErrForbidden

case http.StatusNotFound: // 404
return ErrNotFound

case http.StatusInternalServerError: // 500
return ErrInternal

default:
if resp.StatusCode >= 400 { // for every other error
return fmt.Errorf("Teamweek API returned an unexpected status code: %d", resp.StatusCode)
}
}
return nil
}

// NewClient returns a new Teamweek API client
func NewClient(httpClient *http.Client) *Client {
if httpClient == nil {
httpClient = http.DefaultClient
}
baseURL, _ := url.Parse(defaultBaseURL)
client := &Client{client: httpClient, BaseURL: baseURL, UserAgent: userAgent}
return client
}
92 changes: 92 additions & 0 deletions teamweek/client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package teamweek

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

func TestInvalidURL(t *testing.T) {
client = NewClient(nil)
err := client.get("/%s/error", nil)
if err == nil {
t.Errorf("Expected 'invalid URL escape' error")
}
}

func TestHandleHttpError(t *testing.T) {
setup()
defer teardown()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Bad Request", 400)
})
err := client.get("/", nil)
if err == nil {
t.Errorf("Expected 'Bad Request' error")
}
}

func TestInvalidNewRequest(t *testing.T) {
client = NewClient(nil)
client.BaseURL = &url.URL{Host: "%s"}
err := client.get("/", nil)

if err == nil {
t.Error("Expected error to be returned.")
}
if err, ok := err.(*url.Error); !ok {
t.Errorf("Expected a URL error; got %#v.", err)
}
}

func TestHttpClientError(t *testing.T) {
client = NewClient(nil)
client.BaseURL = &url.URL{}
err := client.get("/", nil)

if err == nil {
t.Error("Expected error to be returned.")
}
if err, ok := err.(*url.Error); !ok {
t.Errorf("Expected a URL error; got %#v.", err)
}
}

func TestServiceInternalError(t *testing.T) {
setup()
defer teardown()

mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Internal Server Error", 500)
})

if err := client.get("/", nil); err == nil {
t.Errorf("Expected 'Internal Server Error'")
}
}

func TestUnauthorizedError(t *testing.T) {
setup()
defer teardown()

mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Unauthorized", 401)
})

if err := client.get("/", nil); err == nil {
t.Errorf("Expected 'Unauthorized'")
}
}

func TestUnexpectedStatus(t *testing.T) {
setup()
defer teardown()

mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Accepted", 442)
})

if err := client.get("/", nil); err == nil {
t.Errorf("Unexpected status code error")
}
}
Loading