Go SDK

Installation

Install the Asguard Go SDK using go get:

go get github.com/org-cyber/asguard/sdks/go

This will download the SDK and make it available in your project.

Setup & Configuration

Configure clients for both Fraud Detection and Face Verification services:

package main

import (
	"context"
	asguard "github.com/org-cyber/asguard/sdks/go"
)

func main() {
	ctx := context.Background()

	// Fraud Detection Client
	fraudConfig := asguard.NewConfiguration()
	fraudConfig.Host = "localhost:8081"
	fraudConfig.Scheme = "http"
	fraudConfig.AddDefaultHeader("X-API-Key", "your-api-key")
	fraudClient := asguard.NewAPIClient(fraudConfig)

	// Face Verification Client
	faceConfig := asguard.NewConfiguration()
	faceConfig.Host = "localhost:8082"
	faceConfig.Scheme = "http"
	faceConfig.AddDefaultHeader("Authorization", "Bearer your-token")
	faceClient := asguard.NewAPIClient(faceConfig)
}
Replace the hosts with your actual service endpoints and use your real API credentials.

Fraud Detection API

Analyzing Transactions

Analyze transactions for fraud using the Fraud Detection API:

ctx := context.Background()

req := asguard.FraudCheckRequest{
	TransactionId: "txn_456",
	Amount:        250000,
	Currency:      "USD",
	UserId:        "user_123",
	DeviceId:      asguard.PtrString("device_789"),
	IpAddress:     asguard.PtrString("192.168.1.5"),
	Location:      asguard.PtrString("Lagos, Nigeria"),
}

result, httpResp, err := fraudClient.FraudDetectionAPI.CheckFraud(ctx).
	FraudCheckRequest(req).
	Execute()

if err != nil {
	fmt.Printf("Error: %v\n", err)
} else {
	fmt.Printf("Risk Level: %s (Score: %.1f)\n", result.RiskLevel, result.RiskScore)
	fmt.Printf("AI Recommendation: %s\n", result.AiRecommendation)
}

Request Fields

Field Type Required Description
user_id string Yes Unique user identifier
transaction_id string Yes Unique transaction identifier
amount number Yes Transaction amount
currency string Yes ISO 4217 currency code
ip_address *string No Source IP address
device_id *string No Device fingerprint
location *string No Geographic location

Response Fields

Field Type Description
risk_score float32 Risk score 0-100
risk_level string LOW, MEDIUM, HIGH, CRITICAL
reasons []string List of reasons
ai_triggered bool Whether AI was triggered
ai_confidence float32 Confidence score 0-1
ai_recommendation string APPROVE, REVIEW, BLOCK, CHALLENGE
ai_fraud_probability float32 Fraud probability 0-1
ai_summary string AI analysis summary

Fraud Detection API Reference

POST /analyze

Analyze a transaction for fraudulent activity.

Example Request

POST http://localhost:8081/analyze
X-API-Key: your-api-key
Content-Type: application/json

{
  "user_id": "user_123",
  "transaction_id": "txn_456",
  "amount": 250000,
  "currency": "USD",
  "ip_address": "192.168.1.5",
  "device_id": "device_789",
  "location": "Lagos, Nigeria"
}

Example Response (200 OK)

{
  "transaction_id": "txn_456",
  "risk_score": 41,
  "risk_level": "MEDIUM",
  "reasons": [
    "High transaction amount (>100k)",
    "Foreign currency transaction (USD)"
  ],
  "ai_triggered": true,
  "ai_confidence": 0.85,
  "ai_recommendation": "REVIEW",
  "ai_fraud_probability": 0.45,
  "ai_summary": "Large USD transaction from Lagos warrants manual review",
  "message": "Transaction analyzed successfully"
}

GET /health

Check service health.

health, _, err := fraudClient.FraudDetectionAPI.Health(ctx).Execute()
// Returns: FraudHealthResponse with status

Face Verification API

Analyzing Faces

Extract facial embeddings and quality metrics:

import (
	"encoding/base64"
	"io/ioutil"
	asguard "github.com/org-cyber/asguard/sdks/go"
)

ctx := context.Background()

// Load and encode image
imageData, err := ioutil.ReadFile("selfie.jpg")
if err != nil {
	fmt.Printf("Error reading file: %v\n", err)
	return
}
base64Image := base64.StdEncoding.EncodeToString(imageData)
dataURI := "data:image/jpeg;base64," + base64Image

// Create request
analyzeReq := asguard.AnalyzeFaceRequest{
	Image:         dataURI,
	QualityChecks: asguard.PtrBool(true),
}

// Execute
analyzeResp, _, err := faceClient.FaceVerificationAPI.AnalyzeFace(ctx).
	AnalyzeFaceRequest(analyzeReq).
	Execute()

if err != nil {
	fmt.Printf("Error: %v\n", err)
} else if analyzeResp.Success {
	fmt.Printf("Embedding: %d dimensions\n", len(analyzeResp.Embedding))
	fmt.Printf("Quality: %.2f\n", *analyzeResp.QualityScore)
}

Request Fields

Field Type Required Description
image string Yes Base64-encoded image (data URI)
quality_checks *bool No Enable quality metrics

Response Fields

Field Type Description
success bool Whether analysis succeeded
face_detected bool Whether a face was detected
embedding []float32 128-dimensional embedding
quality_score *float32 Overall quality (0-1)
sharpness *float32 Image sharpness metric
brightness *float32 Average brightness
face_size_ratio *float32 Face to image size ratio
processing_time_ms *int32 Processing time

Comparing Faces

Compare two faces for identity verification:

ctx := context.Background()

// Create comparison request
compareReq := asguard.CompareFacesRequest{
	ProbeImage:         probeURI,  // Base64-encoded image
	ReferenceEmbedding: embedding,  // From analyze
	Threshold:          asguard.PtrFloat32(0.6),
}

// Execute
compareResp, _, err := faceClient.FaceVerificationAPI.CompareFaces(ctx).
	CompareFacesRequest(compareReq).
	Execute()

if err != nil {
	fmt.Printf("Error: %v\n", err)
} else if compareResp.Success {
	fmt.Printf("Match: %v\n", compareResp.Match)
	fmt.Printf("Confidence: %.2f\n", compareResp.Confidence)
	fmt.Printf("Distance: %.4f\n", compareResp.Distance)
}

Request Fields

Field Type Required Description
probe_image string Yes Base64-encoded image
reference_embedding []float32 Yes 128D reference embedding
threshold *float32 No Confidence threshold

Response Fields

Field Type Description
success bool Whether comparison succeeded
match bool Whether faces match
confidence float32 Confidence score (0-1)
distance float32 Euclidean distance
threshold_used *float32 Applied threshold
probe_quality *float32 Probe image quality
processing_time_ms *int32 Processing time

Face Verification API Reference

POST /v1/analyze

Extract facial embeddings and quality metrics.

Example Request

POST http://localhost:8082/v1/analyze
Authorization: Bearer your-token
Content-Type: application/json

{
  "image": "data:image/jpeg;base64,/9j/4AAQSkZJRg...",
  "quality_checks": true
}

Example Response (200 OK)

{
  "success": true,
  "face_detected": true,
  "embedding": [0.023, -0.14, 0.082, ...],
  "quality_score": 1.0,
  "sharpness": 0.82,
  "brightness": 142.5,
  "face_size_ratio": 0.34,
  "warnings": [],
  "processing_time_ms": 312
}

POST /v1/compare

Compare a probe image against a reference embedding.

Example Request

POST http://localhost:8082/v1/compare
Authorization: Bearer your-token
Content-Type: application/json

{
  "probe_image": "data:image/jpeg;base64,/9j/4AAQSkZJRg...",
  "reference_embedding": [0.023, -0.14, 0.082, ...],
  "threshold": 0.6
}

Example Response (200 OK)

{
  "success": true,
  "match": true,
  "confidence": 0.78,
  "distance": 0.131,
  "threshold_used": 0.6,
  "probe_quality": 1.0,
  "processing_time_ms": 287
}

GET /health

Check service health and version.

GET http://localhost:8082/health

Response: { "status": "healthy", "service": "asguard-face", "version": "1.0.0" }

Pointer Utility Functions

Go requires pointers for optional fields. The SDK provides helper functions:

// Boolean pointer
asguard.PtrBool(true)
asguard.PtrBool(false)

// Integer pointer
asguard.PtrInt(42)
asguard.PtrInt32(100)

// String pointer
asguard.PtrString("value")

// Float pointers
asguard.PtrFloat32(0.5)
asguard.PtrFloat64(0.75)

Use these when constructing requests with optional parameters:

req := asguard.CompareFacesRequest{
	ProbeImage:         probeURI,
	ReferenceEmbedding: embedding,
	Threshold:          asguard.PtrFloat32(0.6),  // Optional
}

Error Handling

Check for errors in the standard Go way:

result, httpResp, err := fraudClient.FraudDetectionAPI.CheckFraud(ctx).
	FraudCheckRequest(req).
	Execute()

if err != nil {
	fmt.Printf("Error: %v\n", err)
	if httpResp != nil {
		fmt.Printf("Status: %d\n", httpResp.StatusCode)
	}
	return
}

// Use result safely
fmt.Printf("Risk Level: %s\n", result.RiskLevel)

HTTP Status Codes

Code Meaning Action
200 Success Process response normally
400 Bad Request Check input parameters
401 Unauthorized Verify credentials
429 Rate Limited Implement backoff
500 Server Error Retry with backoff

Best Practices

Image Encoding

Properly encode images for API submission:

import (
	"encoding/base64"
	"io/ioutil"
)

func encodeImageAsDataURI(filePath string, mimeType string) (string, error) {
	data, err := ioutil.ReadFile(filePath)
	if err != nil {
		return "", err
	}
	encoded := base64.StdEncoding.EncodeToString(data)
	return "data:" + mimeType + ";base64," + encoded, nil
}

// Usage
jpegURI, _ := encodeImageAsDataURI("photo.jpg", "image/jpeg")
pngURI, _ := encodeImageAsDataURI("photo.png", "image/png")

Context Management

Use context for timeouts and cancellation:

import (
	"context"
	"time"
)

// With timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

result, _, err := fraudClient.FraudDetectionAPI.CheckFraud(ctx).
	FraudCheckRequest(req).
	Execute()

Quality Checks

Always enable quality checks for face verification:

analyzeReq := asguard.AnalyzeFaceRequest{
	Image:         dataURI,
	QualityChecks: asguard.PtrBool(true),
}

analyzeResp, _, err := faceClient.FaceVerificationAPI.AnalyzeFace(ctx).
	AnalyzeFaceRequest(analyzeReq).
	Execute()

if analyzeResp.QualityScore != nil && *analyzeResp.QualityScore < 0.7 {
	log.Printf("Warning: Low image quality: %.2f", *analyzeResp.QualityScore)
}

Threshold Selection

Configure thresholds appropriately:

// High security
strictThreshold := asguard.PtrFloat32(0.75)

// Standard
standardThreshold := asguard.PtrFloat32(0.65)

// Lenient
lenientThreshold := asguard.PtrFloat32(0.55)

compareReq := asguard.CompareFacesRequest{
	ProbeImage:         probeURI,
	ReferenceEmbedding: embedding,
	Threshold:          standardThreshold,
}

Retry Logic

Implement exponential backoff for rate limiting:

import (
	"math"
	"time"
)

func callWithRetry(fn func() error, maxRetries int) error {
	for attempt := 0; attempt < maxRetries; attempt++ {
		err := fn()
		if err == nil {
			return nil
		}
		
		// Check if rate limited (429)
		// If so, implement backoff
		waitTime := time.Duration(math.Pow(2, float64(attempt))) * time.Second
		time.Sleep(waitTime)
	}
	return fmt.Errorf("max retries exceeded")
}