Created
February 15, 2018 12:39
-
-
Save rheinardkorf/defb8f746c005346e5de4f58386d39c6 to your computer and use it in GitHub Desktop.
Go: BTCMarkets Authentication Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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