Skip to content
......@@ -5,20 +5,20 @@ import (
"fmt"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"os"
"strconv"
"time"
"golang.org/x/net/publicsuffix"
)
// HostURL - Default Leostream URL
const HostURL string = "http://localhost"
// Client struct
type Client struct {
HostURL string
HTTPClient *http.Client
Token string
Auth AuthStruct
CookieJar http.CookieJar
}
// AuthStruct struct
......@@ -42,14 +42,24 @@ func NewClient(host, username, password *string) (*Client, error) {
// Parse the ssl flag to a boolean
ssl_verify, _ := strconv.ParseBool(ssl_verify_env_var)
// Create cookiejar options
options := &cookiejar.Options{
PublicSuffixList: publicsuffix.List, // Use the default public suffix list
}
// Initialize a cookie jar
jar, err := cookiejar.New(options)
if err != nil {
return nil, err
}
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment, TLSClientConfig: &tls.Config{InsecureSkipVerify: ssl_verify},
}
c := Client{
HTTPClient: &http.Client{Timeout: 10 * time.Second, Transport: tr},
// Default Leostream URL
HostURL: HostURL,
CookieJar: jar,
}
if host != nil {
......@@ -84,15 +94,29 @@ func (c *Client) doRequest(req *http.Request, authToken *string) ([]byte, error)
token = *authToken
}
req.Header.Set("Content-Type", "application/json ")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
// Set cookie on request
// TODO - refactor to make cookiejar automatically set cookies on request
u, _ := req.URL.Parse(c.HostURL)
for _, cookie := range c.CookieJar.Cookies(u) {
req.AddCookie(cookie)
}
res, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
// Update the cookie jar with the cookies from the response
// TODO - refactor to make cookiejar automatically set cookies on request
for _, cookie := range res.Cookies() {
//Add the cookie to the cookie jar
c.CookieJar.SetCookies(u, []*http.Cookie{cookie})
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
......