CatFee.IO
Buy Tron EnergyDashboard
English
English
  • Introduction
  • Getting started
    • Quick Start Guide
    • Buy Energy via Direct TRX Transfer
    • Buy Energy via DApp
    • Buy Energy via API
      • API Overview
      • Java Example for Calling API
      • Python Example for Calling API
      • PHP Example for Calling API
      • Node.js Example for Calling API
      • Go Example for Calling API
    • API Supports Idempotency
    • Energy Subleasing Service
    • 💎Telegram Premium Reselling
    • Blockchain Monitoring Service
    • TRON Node Connection Guide
    • Frequently Asked Questions (FAQ)
    • Terms of Service
  • API Reference
    • Account Information
    • Buy Energy
    • Get Order Detail
    • Estimated Order Amount
    • Buy Telegram Premium
  • knowledge base
    • What is TRON Energy?
    • Why Rent Energy on the TRON Network?
    • How to fix “OUT OF ENERGY” error on TRON Transfers?
    • Why Can’t You Use a Centralized Exchange (CEX) Wallet to Buy TRON Energy?
    • What is a Centralized Exchange (CEX)?
    • How Much Energy and Bandwidth Does a USDT Transfer Consume?
    • Why Does the Transfer Fail Even After Renting Energy on TRON?
    • Why Are Some Energy Rentals So Cheap?
  • Telegram Bot
    • How to Create a Telegram Bot and Host It on CatFee?
Powered by GitBook
On this page
  • Prerequisites
  • Sample Code
  • Code Explanation
  • Notes
  • Summary

Was this helpful?

  1. Getting started
  2. Buy Energy via API

Go Example for Calling API

Golang Example for Calling the CatFee.IO Rest API

Prerequisites

You need a valid API Key and API Secret.

Make sure your Go environment has access to standard libraries such as net/http and crypto/hmac.

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()

Generates the current UTC time formatted as an ISO 8601 timestamp using Go’s time package.

buildRequestPath()

Takes a map of query parameters and constructs a full query string appended to the request path. Parameters are joined with &.

generateSignature()

Creates a signature string by concatenating timestamp + method + requestPath, and then signs it using HMAC-SHA256 with the API Secret. The result is Base64 encoded.

createRequest()

Builds the HTTP request with appropriate headers (CF-ACCESS-KEY, CF-ACCESS-SIGN, CF-ACCESS-TIMESTAMP) and sends it using the standard http package.

main()

Defines request method and query parameters, generates timestamp, request path, and signature, builds the final URL, and sends the request. Finally, the response is read and printed.


Notes

API Key and Secret

Make sure to replace APIKey and APISecret with your actual credentials from CatFee.IO.

Query Parameter Order

This example concatenates query parameters directly without sorting. If your application requires sorted parameters, be sure to implement sorting.

Response Handling

The response is read using ioutil.ReadAll(). If the response body is in JSON format, consider using the encoding/json package to parse the response.

HTTP Methods

This example supports POST, but you can change it to GET, PUT, or DELETE depending on your needs.


Summary

This example demonstrates how to securely call the CatFee.IO Rest API using Go, including HMAC-SHA256 signature generation for authentication. You can adjust the code to use different HTTP methods and handle various API responses accordingly.

PreviousNode.js Example for Calling APINextAPI Supports Idempotency

Last updated 19 days ago

Was this helpful?