Skip to content

Instantly share code, notes, and snippets.

@rheinardkorf
Created February 15, 2018 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rheinardkorf/defb8f746c005346e5de4f58386d39c6 to your computer and use it in GitHub Desktop.
Save rheinardkorf/defb8f746c005346e5de4f58386d39c6 to your computer and use it in GitHub Desktop.
Go: BTCMarkets Authentication Example
package main
import (
"crypto/hmac"
"time"
"strconv"
"fmt"
"net/http"
"io/ioutil"
"crypto/sha512"
"encoding/base64"
"bytes"
"os"
)
var (
publicKey = os.Getenv("BTCM_PUBLIC_KEY")
privateKey = os.Getenv("BTCM_PRIVATE_KEY")
apiBase = "https://api.btcmarkets.net"
)
func apiRequest(method, path string, body []byte) ([]byte, error) {
key, _ := base64.StdEncoding.DecodeString(privateKey)
mac := hmac.New(sha512.New, []byte(key))
timestamp := strconv.FormatInt(time.Now().Unix()*1000, 10)
message := fmt.Sprintf("%s\n%s\n%s", path, timestamp, body)
mac.Write([]byte(message))
signature := base64.StdEncoding.EncodeToString(mac.Sum(nil))
client := &http.Client{}
req, err := http.NewRequest(method, apiBase+path, bytes.NewReader(body))
req.Header.Add("Accept", "application/json")
req.Header.Add("Accept-Charset", "UTF-8")
req.Header.Add("Content-Type", "application/json")
req.Header.Add("apiKey", publicKey)
req.Header.Add("timestamp", timestamp)
req.Header.Add("signature", signature)
resp, err := client.Do(req)
if err != nil {
return nil, err
} else {
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
return data, err
}
}
func main() {
data, err := apiRequest("GET", "/account/balance", nil)
if err != nil {
fmt.Printf("The HTTP request failed with error %s\n", err)
} else {
fmt.Println(string(data))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment