building an API client structure with methods

This commit is contained in:
Jacob Windle 2019-11-15 11:16:56 -05:00
parent 4ac35dab07
commit d86d0a775b
2 changed files with 50 additions and 26 deletions

47
client.go Normal file
View File

@ -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
}

29
main.go
View File

@ -4,39 +4,16 @@ import (
"encoding/xml" "encoding/xml"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"os"
"github.com/joho/godotenv"
"github.com/mrjones/oauth"
) )
var endpoint string = "https://api.tradeking.com/v1/"
func main() { func main() {
// Load our environment variables // Load our environment variables
err := godotenv.Load() var api AllyApi
if err != nil { api.Initialize()
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",
},
)
// Set up our HTTP client // 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() defer resp.Body.Close()
b, _ := ioutil.ReadAll(resp.Body) b, _ := ioutil.ReadAll(resp.Body)