From d86d0a775b4ea06b2a2e2cfc5a532097ca41c771 Mon Sep 17 00:00:00 2001 From: Jacob Date: Fri, 15 Nov 2019 11:16:56 -0500 Subject: [PATCH] building an API client structure with methods --- client.go | 47 +++++++++++++++++++++++++++++++++++++++++++++++ main.go | 29 +++-------------------------- 2 files changed, 50 insertions(+), 26 deletions(-) create mode 100644 client.go diff --git a/client.go b/client.go new file mode 100644 index 0000000..2f8c3c0 --- /dev/null +++ b/client.go @@ -0,0 +1,47 @@ +package main + +import ( + "fmt" + "github.com/joho/godotenv" + "github.com/mrjones/oauth" + "net/http" + "os" +) + +/* The trading endpoint for Ally */ +const endpoint string = "https://api.tradeking.com/v1/" + +type AllyApi struct { + consumer *oauth.Consumer + Client *http.Client +} + +func (c *AllyApi) Initialize() { + err := godotenv.Load() + if err != nil { + panic(err) + } + + // Set up our new oauth consumer + c.consumer = oauth.NewConsumer( + os.Getenv("CONSUMER_KEY"), + os.Getenv("CONSUMER_SECRET"), + oauth.ServiceProvider{ + RequestTokenUrl: "https://developers.tradeking.com/oauth/request_token", + AuthorizeTokenUrl: "https://developers.tradeking.com/oauth/authorize", + AccessTokenUrl: "https://developers.tradeking.com/oauth/access_token", + }, + ) + + c.Client, err = c.consumer.MakeHttpClient( + &oauth.AccessToken{Token: os.Getenv("ACCESS_TOKEN"), Secret: os.Getenv("ACCESS_SECRET")}) + + if err != nil { + panic(err) + } +} + +func (c *AllyApi) Get(path string) (resp *http.Response, err error) { + resp, err = c.Client.Get(fmt.Sprintf("%s\\%s", endpoint, path)) + return +} diff --git a/main.go b/main.go index 4b19151..2fcb7a1 100644 --- a/main.go +++ b/main.go @@ -4,39 +4,16 @@ import ( "encoding/xml" "fmt" "io/ioutil" - "os" - - "github.com/joho/godotenv" - "github.com/mrjones/oauth" ) -var endpoint string = "https://api.tradeking.com/v1/" - func main() { // Load our environment variables - err := godotenv.Load() - if err != nil { - panic(err) - } - - // Set up our new oauth consumer - cons := oauth.NewConsumer( - os.Getenv("CONSUMER_KEY"), - os.Getenv("CONSUMER_SECRET"), - oauth.ServiceProvider{ - RequestTokenUrl: "https://developers.tradeking.com/oauth/request_token", - AuthorizeTokenUrl: "https://developers.tradeking.com/oauth/authorize", - AccessTokenUrl: "https://developers.tradeking.com/oauth/access_token", - }, - ) + var api AllyApi + api.Initialize() // Set up our HTTP client - client, err := cons.MakeHttpClient(&oauth.AccessToken{Token: os.Getenv("ACCESS_TOKEN"), Secret: os.Getenv("ACCESS_SECRET")}) - if err != nil { - panic(err) - } - resp, err := client.Get(fmt.Sprintf("%s\\%s", endpoint, "accounts")) + resp, err := api.Get("accounts") defer resp.Body.Close() b, _ := ioutil.ReadAll(resp.Body)