oef/client/client.go

119 lines
2.3 KiB
Go

package client
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"git.andreafazzi.eu/andrea/oef/orm"
"git.andreafazzi.eu/andrea/oef/renderer"
"github.com/jinzhu/inflection"
)
// A client represents a client connection to the Headmaster test
// server.
type Client struct {
Url *url.URL
Username string
Password string
User string
token string
}
// Dial connects to a test server instance at the specified address
// using the given credentials.
func Dial(host, username, password string) (*Client, error) {
url, err := url.Parse(host)
if err != nil {
return nil, err
}
client := &Client{
Url: url,
Username: username,
Password: password,
}
response, err := client.SendRequest("GET", "get_token", nil)
if err != nil {
panic(err)
}
var data struct {
Token string
User string
}
if err := json.Unmarshal(response, &data); err != nil {
panic(err)
}
client.token = data.Token
client.User = data.User
return client, nil
}
func (c *Client) SendRequest(method string, path string, data []byte) ([]byte, error) {
// Create the https request
folderUrl, err := url.Parse(path)
if err != nil {
return nil, err
}
client := &http.Client{}
req, err := http.NewRequest(method, c.Url.ResolveReference(folderUrl).String(), bytes.NewReader(data))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.SetBasicAuth(c.Username, c.Password)
if c.token != "" {
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.token))
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}
func (c *Client) GetAll(model interface{}) error {
var response renderer.JsonResponse
data, err := c.SendRequest("GET", fmt.Sprintf("/api/%s?format=json", pluralizedModelName(model)), nil)
if err != nil {
return err
}
if err := json.Unmarshal(data, &response); err != nil {
return err
}
if string(response.Error) != "" {
return errors.New(string(response.Error))
}
if err := json.Unmarshal(response.Result, &model); err != nil {
return err
}
return nil
}
func pluralizedModelName(value interface{}) string {
return inflection.Plural(strings.ToLower(orm.ModelName(value)))
}