Go Example for Calling API
Golang Example for Calling the CatFee.IO Rest API
Prerequisites
Sample Code
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"net/http"
"net/url"
"time"
"io/ioutil"
"log"
)
const (
APIKey = "your_api_key" // Replace with your actual API Key
APISecret = "your_api_secret" // Replace with your actual API Secret
BaseURL = "https://api.catfee.io"
)
// Generate the current timestamp in ISO 8601 format
func generateTimestamp() string {
return time.Now().UTC().Format("2006-01-02T15:04:05.000Z")
}
// Build request path including query parameters
func buildRequestPath(path string, queryParams map[string]string) string {
if len(queryParams) == 0 {
return path
}
queryString := "?"
for key, value := range queryParams {
queryString += fmt.Sprintf("%s=%s&", key, value)
}
queryString = queryString[:len(queryString)-1] // remove the trailing '&'
return path + queryString
}
// Generate HMAC-SHA256 signature
func generateSignature(timestamp, method, requestPath string) string {
signString := timestamp + method + requestPath
mac := hmac.New(sha256.New, []byte(APISecret))
mac.Write([]byte(signString))
signature := mac.Sum(nil)
return base64.StdEncoding.EncodeToString(signature)
}
// Create and send HTTP request
func createRequest(url, method, timestamp, signature string) (*http.Response, error) {
client := &http.Client{}
req, err := http.NewRequest(method, url, nil)
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("CF-ACCESS-KEY", APIKey)
req.Header.Add("CF-ACCESS-SIGN", signature)
req.Header.Add("CF-ACCESS-TIMESTAMP", timestamp)
return client.Do(req)
}
func main() {
method := "POST" // Can be "GET", "PUT", or "DELETE"
path := "/v1/order"
// Example: Create order
queryParams := map[string]string{
"quantity": "65000",
"receiver": "TRON_ADDRESS",
"duration": "1h",
}
timestamp := generateTimestamp()
requestPath := buildRequestPath(path, queryParams)
signature := generateSignature(timestamp, method, requestPath)
url := BaseURL + requestPath
resp, err := createRequest(url, method, timestamp, signature)
if err != nil {
log.Fatal("Error making request:", err)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal("Error reading response:", err)
}
fmt.Println("Response Status:", resp.Status)
fmt.Println("Response Body:", string(body))
}Code Explanation
generateTimestamp()
generateTimestamp()buildRequestPath()
buildRequestPath()generateSignature()
generateSignature()createRequest()
createRequest()main()
main()Notes
API Key and Secret
Query Parameter Order
Response Handling
HTTP Methods
Summary
Last updated