Skip to content

Commit

Permalink
Initial version
Browse files Browse the repository at this point in the history
  • Loading branch information
koen-serry committed Jul 4, 2021
0 parents commit 3ccc005
Show file tree
Hide file tree
Showing 13 changed files with 1,012 additions and 0 deletions.
17 changes: 17 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib

# Test binary, built with `go test -c`
*.test

# Output of the go coverage tool, specifically when used with LiteIDE
*.out

# Dependency directories (remove the comment below to include it)
# vendor/

*.iml
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Twikey Go Api
=======

Initial version more to come
94 changes: 94 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package twikey

import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"time"
)

const (
BaseURLV1 = "https://api.twikey.com"
TWIKEY_VERSION = "twikey-api/go"
)

type TwikeyClient struct {
BaseURL string
ApiKey string
PrivateKey string
Salt string
UserAgent string

HTTPClient *http.Client

Debug *log.Logger

apiToken string
lastLogin time.Time
}

func NewClient(apiKey string) *TwikeyClient {
return &TwikeyClient{
BaseURL: BaseURLV1,
ApiKey: apiKey,
Salt: "own",
HTTPClient: &http.Client{
Timeout: time.Minute,
},
}
}

type errorResponse struct {
Code string `json:"code"`
Message string `json:"message"` // translated according to Accept-Language
Extra string `json:"extra"`
}

func (c *TwikeyClient) debug(v ...interface{}) {
if c.Debug != nil {
c.Debug.Println(v...)
}
}

func (c *TwikeyClient) error(v ...interface{}) {
if c.Debug != nil {
c.Debug.Fatal(v...)
}
}

func (c *TwikeyClient) sendRequest(req *http.Request, v interface{}) error {

if err := c.refreshTokenIfRequired(); err != nil {
return err
}

req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", c.UserAgent)
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", c.apiToken)

c.debug(req.Body)

res, err := c.HTTPClient.Do(req)
if err != nil {
return err
}

defer res.Body.Close()

if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
var errRes errorResponse
if err = json.NewDecoder(res.Body).Decode(&errRes); err == nil {
return errors.New(errRes.Message)
}
return fmt.Errorf("Unknown error, status code: %d", res.StatusCode)
}

if err = json.NewDecoder(res.Body).Decode(v); err != nil {
return err
}

return nil
}
Loading

0 comments on commit 3ccc005

Please sign in to comment.