Go Package Reference
Go Examples

TELA API Examples

Comprehensive examples demonstrating real-world usage of the TELA Go package.

Complete Application Deployment

This example shows the full workflow of creating and deploying a TELA application.

package main
 
import (
    "fmt"
    "log"
    "os"
    "path/filepath"
    "github.com/civilware/tela"
    "github.com/deroproject/derohe/walletapi"
)
 
func main() {
    // Load wallet
    wallet, err := walletapi.Create_Encrypted_Wallet_From_Recovery_Words(
        "./wallet.db", 
        "password123", 
        "your recovery words here",
    )
    if err != nil {
        log.Fatal("Failed to load wallet:", err)
    }
    
    // Deploy a complete TELA application
    indexSCID, err := deployTELAApp(wallet)
    if err != nil {
        log.Fatal("Deployment failed:", err)
    }
    
    fmt.Printf("🎉 TELA app deployed successfully!\n")
    fmt.Printf("INDEX SCID: %s\n", indexSCID)
    
    // Serve the deployed application
    endpoint := "127.0.0.1:10102"
    link, err := tela.ServeTELA(indexSCID, endpoint)
    if err != nil {
        log.Fatal("Failed to serve app:", err)
    }
    
    fmt.Printf("🌐 App running at: %s\n", link)
    
    // Keep the server running
    fmt.Println("Press Ctrl+C to stop the server...")
    select {} // Block forever
}
 
func deployTELAApp(wallet *walletapi.Wallet_Disk) (string, error) {
    fmt.Println("📦 Deploying TELA Application...")
    
    // 1. Create HTML DOC
    htmlContent := `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My TELA App</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <h1>Welcome to My TELA App</h1>
        <p>This is a decentralized web application running on TELA!</p>
        <button onclick="showMessage()">Click Me</button>
        <div id="message"></div>
    </div>
    <script src="app.js"></script>
</body>
</html>`
    
    htmlDOC := &tela.DOC{
        DocType: tela.DOC_HTML,
        Code:    htmlContent,
        DURL:    "myapp.tela",
        Headers: tela.Headers{
            NameHdr:  "index.html",
            DescrHdr: "Main HTML page",
        },
    }
    
    // 2. Create CSS DOC
    cssContent := `body {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
    margin: 0;
    padding: 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    min-height: 100vh;
}
 
.container {
    max-width: 600px;
    margin: 0 auto;
    background: white;
    padding: 40px;
    border-radius: 10px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.2);
    text-align: center;
}
 
h1 {
    color: #333;
    margin-bottom: 20px;
}
 
button {
    background: #667eea;
    color: white;
    border: none;
    padding: 12px 24px;
    border-radius: 6px;
    cursor: pointer;
    font-size: 16px;
    margin: 20px 0;
}
 
button:hover {
    background: #5a6fd8;
}
 
#message {
    margin-top: 20px;
    padding: 15px;
    background: #f0f8ff;
    border-radius: 6px;
    display: none;
}`
    
    cssDOC := &tela.DOC{
        DocType: tela.DOC_CSS,
        Code:    cssContent,
        DURL:    "myapp.tela",
        Headers: tela.Headers{
            NameHdr:  "style.css",
            DescrHdr: "Application styles",
        },
    }
    
    // 3. Create JavaScript DOC
    jsContent := `function showMessage() {
    const messageDiv = document.getElementById('message');
    const messages = [
        '🎉 Hello from the decentralized web!',
        '🚀 TELA makes web apps truly decentralized!',
        '🔒 Your privacy is protected by DERO blockchain!',
        '🌐 Welcome to the future of the internet!'
    ];
    
    const randomMessage = messages[Math.floor(Math.random() * messages.length)];
    messageDiv.textContent = randomMessage;
    messageDiv.style.display = 'block';
    
    // Add some animation
    messageDiv.style.opacity = '0';
    setTimeout(() => {
        messageDiv.style.transition = 'opacity 0.5s';
        messageDiv.style.opacity = '1';
    }, 100);
}
 
// Add some interactivity
document.addEventListener('DOMContentLoaded', function() {
    console.log('🎯 TELA app loaded successfully!');
    
    // Add click animation to button
    const button = document.querySelector('button');
    button.addEventListener('click', function() {
        this.style.transform = 'scale(0.95)';
        setTimeout(() => {
            this.style.transform = 'scale(1)';
        }, 150);
    });
});`
    
    jsDOC := &tela.DOC{
        DocType: tela.DOC_JS,
        Code:    jsContent,
        DURL:    "myapp.tela",
        Headers: tela.Headers{
            NameHdr:  "app.js",
            DescrHdr: "Application JavaScript",
        },
    }
    
    // 4. Deploy all DOCs
    docs := []*tela.DOC{htmlDOC, cssDOC, jsDOC}
    var docSCIDs []string
    
    for i, doc := range docs {
        fmt.Printf("Deploying DOC %d/3: %s\n", i+1, doc.Headers.NameHdr)
        
        txid, err := tela.Installer(wallet, 2, doc)
        if err != nil {
            return "", fmt.Errorf("failed to deploy %s: %v", doc.Headers.NameHdr, err)
        }
        
        // In a real application, you would wait for confirmation and get the actual SCID
        // For this example, we'll use the TXID as SCID (this is not correct in practice)
        docSCIDs = append(docSCIDs, txid)
        fmt.Printf("✅ DOC deployed: %s\n", txid)
    }
    
    // 5. Create and deploy INDEX
    index := &tela.INDEX{
        DURL: "myapp.tela",
        DOCs: docSCIDs,
        Mods: "vsoo", // Add variable storage capability
        Headers: tela.Headers{
            NameHdr:  "My TELA App",
            DescrHdr: "A sample decentralized web application",
            IconHdr:  "https://example.com/icon.png",
        },
    }
    
    fmt.Println("Deploying INDEX...")
    indexTXID, err := tela.Installer(wallet, 2, index)
    if err != nil {
        return "", fmt.Errorf("failed to deploy INDEX: %v", err)
    }
    
    fmt.Printf("✅ INDEX deployed: %s\n", indexTXID)
    return indexTXID, nil
}

Content Management System

Example of a more complex application with content management features.

package main
 
import (
    "fmt"
    "log"
    "github.com/civilware/tela"
    "github.com/deroproject/derohe/walletapi"
)
 
type ContentManager struct {
    wallet   *walletapi.Wallet_Disk
    endpoint string
    indexSCID string
}
 
func NewContentManager(wallet *walletapi.Wallet_Disk, endpoint, indexSCID string) *ContentManager {
    return &ContentManager{
        wallet:    wallet,
        endpoint:  endpoint,
        indexSCID: indexSCID,
    }
}
 
// Rate content based on quality assessment
func (cm *ContentManager) RateContent(scid string, quality, functionality int) error {
    // Create structured rating (quality * 10 + functionality)
    rating := uint64(quality*10 + functionality)
    
    fmt.Printf("Rating content %s: %d\n", scid[:12]+"...", rating)
    
    txid, err := tela.Rate(cm.wallet, scid, rating)
    if err != nil {
        return fmt.Errorf("rating failed: %v", err)
    }
    
    fmt.Printf("✅ Rating submitted: %s\n", txid)
    return nil
}
 
// Get comprehensive content information
func (cm *ContentManager) GetContentInfo(scid string) error {
    fmt.Printf("📊 Content Analysis: %s\n", scid[:12]+"...")
    
    // Try to get as INDEX first
    index, err := tela.GetINDEXInfo(scid, cm.endpoint)
    if err == nil {
        fmt.Printf("📱 Application: %s\n", index.Headers.NameHdr)
        fmt.Printf("   Description: %s\n", index.Headers.DescrHdr)
        fmt.Printf("   Author: %s\n", index.Author)
        fmt.Printf("   dURL: %s\n", index.DURL)
        fmt.Printf("   MODs: %s\n", index.Mods)
        fmt.Printf("   DOCs: %d\n", len(index.DOCs))
        
        // Analyze each DOC
        for i, docSCID := range index.DOCs {
            fmt.Printf("   DOC%d: %s\n", i+1, docSCID[:12]+"...")
            
            doc, err := tela.GetDOCInfo(docSCID, cm.endpoint)
            if err == nil {
                fmt.Printf("     File: %s (%s)\n", doc.Headers.NameHdr, doc.DocType)
                if doc.SubDir != "" {
                    fmt.Printf("     Directory: %s\n", doc.SubDir)
                }
            }
        }
    } else {
        // Try as DOC
        doc, err := tela.GetDOCInfo(scid, cm.endpoint)
        if err == nil {
            fmt.Printf("📄 Document: %s\n", doc.Headers.NameHdr)
            fmt.Printf("   Type: %s\n", doc.DocType)
            fmt.Printf("   Author: %s\n", doc.Author)
            fmt.Printf("   dURL: %s\n", doc.DURL)
            
            if doc.Compression != "" {
                fmt.Printf("   Compression: %s\n", doc.Compression)
            }
            
            // Extract and analyze content
            content, err := doc.ExtractDocCode()
            if err == nil {
                size := tela.GetCodeSizeInKB(content)
                fmt.Printf("   Content Size: %.2f KB\n", size)
            }
        } else {
            return fmt.Errorf("content not found or invalid: %v", err)
        }
    }
    
    // Get ratings
    ratings, err := tela.GetRating(scid, cm.endpoint, 0)
    if err == nil {
        fmt.Printf("\n⭐ Community Ratings:\n")
        fmt.Printf("   Likes: %d | Dislikes: %d\n", ratings.Likes, ratings.Dislikes)
        fmt.Printf("   Average: %.1f (%s)\n", ratings.Average, ratings.ParseAverage())
        fmt.Printf("   Total Ratings: %d\n", len(ratings.Ratings))
        
        // Show recent ratings
        if len(ratings.Ratings) > 0 {
            fmt.Printf("   Recent Ratings:\n")
            for i, rating := range ratings.Ratings {
                if i >= 3 { // Show only first 3
                    break
                }
                ratingStr, _ := tela.Ratings.ParseString(rating.Rating)
                fmt.Printf("     %s: %s\n", rating.Address[:12]+"...", ratingStr)
            }
        }
    }
    
    return nil
}
 
// Set metadata for content
func (cm *ContentManager) SetMetadata(scid, key, value string) error {
    fmt.Printf("Setting metadata: %s = %s\n", key, value)
    
    txid, err := tela.SetVar(cm.wallet, scid, key, value)
    if err != nil {
        return fmt.Errorf("failed to set metadata: %v", err)
    }
    
    fmt.Printf("✅ Metadata set: %s\n", txid)
    return nil
}
 
// Comprehensive content discovery
func (cm *ContentManager) DiscoverContent(scid string) error {
    fmt.Printf("🔍 Content Discovery: %s\n", scid)
    
    // Serve the content
    link, err := tela.ServeTELA(scid, cm.endpoint)
    if err != nil {
        return fmt.Errorf("failed to serve content: %v", err)
    }
    
    fmt.Printf("🌐 Content served at: %s\n", link)
    
    // Get detailed information
    if err := cm.GetContentInfo(scid); err != nil {
        fmt.Printf("⚠️ Could not get detailed info: %v\n", err)
    }
    
    return nil
}
 
func main() {
    // Setup
    wallet, err := loadWallet() // Your wallet loading logic
    if err != nil {
        log.Fatal("Failed to load wallet:", err)
    }
    
    cm := NewContentManager(wallet, "127.0.0.1:10102", "your-index-scid-here")
    
    // Example usage
    contentSCID := "f2815b442d62a055e4bb8913167e3dbce3208f300d7006aaa3a2f127b06de29d"
    
    // Discover and analyze content
    if err := cm.DiscoverContent(contentSCID); err != nil {
        log.Printf("Discovery failed: %v", err)
    }
    
    // Set some metadata
    cm.SetMetadata(contentSCID, "var_meta_category", "Productivity")
    cm.SetMetadata(contentSCID, "var_owners_note", "Maintained and updated regularly")
    
    // Rate the content
    cm.RateContent(contentSCID, 8, 7) // Very good, Works well
}
 
func loadWallet() (*walletapi.Wallet_Disk, error) {
    // Your wallet loading logic here
    return nil, fmt.Errorf("implement wallet loading")
}

TELA Link Handler Service

A web service that handles TELA links and provides HTTP endpoints.

package main
 
import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "strings"
    "sync"
    "time"
    "github.com/civilware/tela"
)
 
type TELAService struct {
    endpoint    string
    serverCache map[string]string
    mu          sync.RWMutex
}
 
type LinkRequest struct {
    Link string `json:"link"`
}
 
type LinkResponse struct {
    Success bool   `json:"success"`
    URL     string `json:"url,omitempty"`
    Error   string `json:"error,omitempty"`
    Info    *ContentInfo `json:"info,omitempty"`
}
 
type ContentInfo struct {
    Type        string `json:"type"`
    Name        string `json:"name"`
    Description string `json:"description"`
    Author      string `json:"author"`
    DURL        string `json:"durl"`
}
 
func NewTELAService(endpoint string) *TELAService {
    return &TELAService{
        endpoint:    endpoint,
        serverCache: make(map[string]string),
    }
}
 
func (ts *TELAService) handleOpenLink(w http.ResponseWriter, r *http.Request) {
    var req LinkRequest
    if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
        http.Error(w, "Invalid request", http.StatusBadRequest)
        return
    }
    
    // Parse TELA link
    target, args, err := tela.ParseTELALink(req.Link)
    if err != nil {
        response := LinkResponse{
            Success: false,
            Error:   fmt.Sprintf("Invalid TELA link: %v", err),
        }
        json.NewEncoder(w).Encode(response)
        return
    }
    
    if target != "tela" || len(args) < 2 {
        response := LinkResponse{
            Success: false,
            Error:   "Invalid TELA link format",
        }
        json.NewEncoder(w).Encode(response)
        return
    }
    
    scid := args[1]
    
    // Check cache first
    ts.mu.RLock()
    cachedURL, exists := ts.serverCache[scid]
    ts.mu.RUnlock()
    
    var httpURL string
    if exists {
        // Build URL with path
        httpURL = cachedURL
        if len(args) > 2 {
            httpURL += "/" + strings.Join(args[2:], "/")
        }
    } else {
        // Open the TELA link
        httpURL, err = tela.OpenTELALink(req.Link, ts.endpoint)
        if err != nil {
            response := LinkResponse{
                Success: false,
                Error:   fmt.Sprintf("Failed to open TELA link: %v", err),
            }
            json.NewEncoder(w).Encode(response)
            return
        }
        
        // Cache the base URL
        ts.mu.Lock()
        if baseURL := extractBaseURL(httpURL); baseURL != "" {
            ts.serverCache[scid] = baseURL
        }
        ts.mu.Unlock()
    }
    
    // Get content information
    var info *ContentInfo
    if index, err := tela.GetINDEXInfo(scid, ts.endpoint); err == nil {
        info = &ContentInfo{
            Type:        "Application",
            Name:        index.Headers.NameHdr,
            Description: index.Headers.DescrHdr,
            Author:      index.Author,
            DURL:        index.DURL,
        }
    } else if doc, err := tela.GetDOCInfo(scid, ts.endpoint); err == nil {
        info = &ContentInfo{
            Type:        "Document",
            Name:        doc.Headers.NameHdr,
            Description: doc.Headers.DescrHdr,
            Author:      doc.Author,
            DURL:        doc.DURL,
        }
    }
    
    response := LinkResponse{
        Success: true,
        URL:     httpURL,
        Info:    info,
    }
    
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(response)
}
 
func (ts *TELAService) handleServerInfo(w http.ResponseWriter, r *http.Request) {
    servers := tela.GetServerInfo()
    
    type ServerStatus struct {
        Name       string `json:"name"`
        Address    string `json:"address"`
        SCID       string `json:"scid"`
        Entrypoint string `json:"entrypoint"`
        URL        string `json:"url"`
    }
    
    var status []ServerStatus
    for _, server := range servers {
        status = append(status, ServerStatus{
            Name:       server.Name,
            Address:    server.Address,
            SCID:       server.SCID,
            Entrypoint: server.Entrypoint,
            URL:        fmt.Sprintf("http://localhost%s/%s", server.Address, server.Entrypoint),
        })
    }
    
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(map[string]interface{}{
        "servers": status,
        "count":   len(status),
    })
}
 
func (ts *TELAService) handleShutdown(w http.ResponseWriter, r *http.Request) {
    serverName := r.URL.Query().Get("server")
    
    if serverName == "" {
        // Shutdown all
        tela.ShutdownTELA()
        ts.mu.Lock()
        ts.serverCache = make(map[string]string)
        ts.mu.Unlock()
        
        json.NewEncoder(w).Encode(map[string]interface{}{
            "success": true,
            "message": "All servers shutdown",
        })
    } else {
        // Shutdown specific server
        tela.ShutdownServer(serverName)
        
        json.NewEncoder(w).Encode(map[string]interface{}{
            "success": true,
            "message": fmt.Sprintf("Server %s shutdown", serverName),
        })
    }
}
 
func extractBaseURL(fullURL string) string {
    if idx := strings.LastIndex(fullURL, "/"); idx > 7 {
        return fullURL[:idx]
    }
    return fullURL
}
 
func main() {
    // Configure TELA
    tela.SetPortStart(8090)
    tela.SetMaxServers(10)
    tela.AllowUpdates(true)
    
    service := NewTELAService("127.0.0.1:10102")
    
    // Setup routes
    http.HandleFunc("/api/open", service.handleOpenLink)
    http.HandleFunc("/api/servers", service.handleServerInfo)
    http.HandleFunc("/api/shutdown", service.handleShutdown)
    
    // Serve static files for the web interface
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        if r.URL.Path == "/" {
            fmt.Fprint(w, `<!DOCTYPE html>
<html>
<head>
    <title>TELA Link Handler</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        .container { max-width: 800px; margin: 0 auto; }
        input[type="text"] { width: 500px; padding: 10px; margin: 10px; }
        button { padding: 10px 20px; margin: 10px; }
        .result { margin: 20px 0; padding: 15px; background: #f0f0f0; }
    </style>
</head>
<body>
    <div class="container">
        <h1>TELA Link Handler</h1>
        <div>
            <input type="text" id="telaLink" placeholder="Enter TELA link (tela://open/scid/path)">
            <button onclick="openLink()">Open Link</button>
        </div>
        <div>
            <button onclick="getServers()">Show Servers</button>
            <button onclick="shutdownAll()">Shutdown All</button>
        </div>
        <div id="result" class="result" style="display:none;"></div>
    </div>
    
    <script>
        async function openLink() {
            const link = document.getElementById('telaLink').value;
            if (!link) return;
            
            try {
                const response = await fetch('/api/open', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ link: link })
                });
                
                const result = await response.json();
                const resultDiv = document.getElementById('result');
                
                if (result.success) {
                    resultDiv.innerHTML = 
                        '<h3>✅ Success!</h3>' +
                        '<p><strong>URL:</strong> <a href="' + result.url + '" target="_blank">' + result.url + '</a></p>' +
                        (result.info ? 
                            '<p><strong>Type:</strong> ' + result.info.type + '</p>' +
                            '<p><strong>Name:</strong> ' + result.info.name + '</p>' +
                            '<p><strong>Description:</strong> ' + result.info.description + '</p>'
                        : '');
                    window.open(result.url, '_blank');
                } else {
                    resultDiv.innerHTML = '<h3>❌ Error</h3><p>' + result.error + '</p>';
                }
                
                resultDiv.style.display = 'block';
            } catch (error) {
                document.getElementById('result').innerHTML = '<h3>❌ Error</h3><p>' + error.message + '</p>';
                document.getElementById('result').style.display = 'block';
            }
        }
        
        async function getServers() {
            try {
                const response = await fetch('/api/servers');
                const result = await response.json();
                
                let html = '<h3>🖥️ Running Servers (' + result.count + ')</h3>';
                if (result.servers.length === 0) {
                    html += '<p>No servers running</p>';
                } else {
                    html += '<ul>';
                    result.servers.forEach(server => {
                        html += '<li><strong>' + server.name + '</strong> - ' +
                               '<a href="' + server.url + '" target="_blank">' + server.url + '</a></li>';
                    });
                    html += '</ul>';
                }
                
                document.getElementById('result').innerHTML = html;
                document.getElementById('result').style.display = 'block';
            } catch (error) {
                console.error('Error getting servers:', error);
            }
        }
        
        async function shutdownAll() {
            if (!confirm('Shutdown all TELA servers?')) return;
            
            try {
                const response = await fetch('/api/shutdown', { method: 'POST' });
                const result = await response.json();
                
                document.getElementById('result').innerHTML = 
                    '<h3>🛑 ' + result.message + '</h3>';
                document.getElementById('result').style.display = 'block';
            } catch (error) {
                console.error('Error shutting down:', error);
            }
        }
    </script>
</body>
</html>`)
        }
    })
    
    fmt.Println("🚀 TELA Link Handler Service starting on :8080")
    fmt.Println("📱 Web interface: http://localhost:8080")
    fmt.Println("🔗 API endpoints:")
    fmt.Println("   POST /api/open - Open TELA links")
    fmt.Println("   GET  /api/servers - List running servers")
    fmt.Println("   POST /api/shutdown - Shutdown servers")
    
    // Graceful shutdown
    go func() {
        time.Sleep(100 * time.Millisecond) // Let the server start
        fmt.Println("✅ Service ready!")
    }()
    
    log.Fatal(http.ListenAndServe(":8080", nil))
}

File Processing Pipeline

Example showing comprehensive file processing for TELA deployment.

package main
 
import (
    "fmt"
    "io/fs"
    "os"
    "path/filepath"
    "strings"
    "github.com/civilware/tela"
)
 
type ProcessingResult struct {
    OriginalSize   float64
    ProcessedSize  float64
    Compressed     bool
    Sharded        bool
    ShardCount     int
    DOC           *tela.DOC
    ShardFiles    []string
}
 
func processFileForTELA(filePath string) (*ProcessingResult, error) {
    content, err := os.ReadFile(filePath)
    if err != nil {
        return nil, err
    }
    
    fileName := filepath.Base(filePath)
    docType := tela.ParseDocType(fileName)
    originalSize := tela.GetCodeSizeInKB(string(content))
    
    result := &ProcessingResult{
        OriginalSize: originalSize,
    }
    
    fmt.Printf("Processing: %s (%.2fKB, %s)\n", fileName, originalSize, docType)
    
    // Check if file type is supported
    if !tela.IsAcceptedLanguage(docType) {
        return nil, fmt.Errorf("unsupported file type: %s", docType)
    }
    
    var finalContent []byte = content
    var compression string
    
    // Apply compression if beneficial
    if originalSize > 10.0 {
        compressed, err := tela.Compress(content, ".gz")
        if err == nil {
            compressedBytes := []byte(compressed)
            compressedSize := tela.GetCodeSizeInKB(compressed)
            
            // Use compression if it reduces size by at least 20%
            if compressedSize < originalSize*0.8 {
                finalContent = compressedBytes
                compression = ".gz"
                result.Compressed = true
                result.ProcessedSize = compressedSize
                fileName += ".gz"
                fmt.Printf("  Compressed: %.2fKB -> %.2fKB (%.1f%% reduction)\n",
                    originalSize, compressedSize, (1-compressedSize/originalSize)*100)
            } else {
                result.ProcessedSize = originalSize
                fmt.Printf("  Compression not beneficial, using original\n")
            }
        } else {
            result.ProcessedSize = originalSize
            fmt.Printf("  Compression failed: %v\n", err)
        }
    } else {
        result.ProcessedSize = originalSize
    }
    
    // Check if sharding is needed
    finalSize := tela.GetCodeSizeInKB(string(finalContent))
    if finalSize > 18.0 {
        fmt.Printf("  File too large (%.2fKB), creating shards...\n", finalSize)
        
        // Create shard files
        shardDir := filepath.Join(filepath.Dir(filePath), "shards")
        os.MkdirAll(shardDir, 0755)
        
        shardPath := filepath.Join(shardDir, fileName)
        err = tela.CreateShardFiles(shardPath, compression, finalContent)
        if err != nil {
            return nil, fmt.Errorf("sharding failed: %v", err)
        }
        
        shardCount, _ := tela.GetTotalShards(finalContent)
        result.Sharded = true
        result.ShardCount = shardCount
        
        // List shard files
        for i := 1; i <= shardCount; i++ {
            ext := filepath.Ext(fileName)
            name := strings.TrimSuffix(fileName, ext)
            shardFile := fmt.Sprintf("%s-%d%s", name, i, ext)
            result.ShardFiles = append(result.ShardFiles, filepath.Join(shardDir, shardFile))
        }
        
        fmt.Printf("  Created %d shard files\n", shardCount)
        return result, nil
    }
    
    // Create regular DOC
    subDir := ""
    if dir := filepath.Dir(filePath); dir != "." {
        subDir = dir
    }
    
    doc := &tela.DOC{
        DocType:     docType,
        Code:        string(finalContent),
        SubDir:      subDir,
        DURL:        fmt.Sprintf("%s.tela", strings.TrimSuffix(fileName, filepath.Ext(fileName))),
        Compression: compression,
        Headers: tela.Headers{
            NameHdr:  fileName,
            DescrHdr: fmt.Sprintf("Processed from %s", filePath),
        },
    }
    
    result.DOC = doc
    fmt.Printf("  ✅ Ready for deployment (%.2fKB)\n", finalSize)
    
    return result, nil
}
 
func processDirectoryForTELA(dirPath string) error {
    var docs []*tela.DOC
    var shardFiles []string
    totalOriginalSize := 0.0
    totalProcessedSize := 0.0
    compressedCount := 0
    shardedCount := 0
    
    fmt.Printf("🔄 Processing directory: %s\n", dirPath)
    
    err := filepath.WalkDir(dirPath, func(path string, d fs.DirEntry, err error) error {
        if err != nil || d.IsDir() {
            return err
        }
        
        // Skip existing shard files
        if strings.Contains(d.Name(), "-") && 
           (strings.Contains(d.Name(), ".gz") || strings.Contains(d.Name(), ".")) {
            return nil
        }
        
        result, err := processFileForTELA(path)
        if err != nil {
            fmt.Printf("  ❌ Error processing %s: %v\n", d.Name(), err)
            return nil // Continue with other files
        }
        
        totalOriginalSize += result.OriginalSize
        totalProcessedSize += result.ProcessedSize
        
        if result.Compressed {
            compressedCount++
        }
        
        if result.Sharded {
            shardedCount++
            shardFiles = append(shardFiles, result.ShardFiles...)
        } else if result.DOC != nil {
            docs = append(docs, result.DOC)
        }
        
        return nil
    })
    
    if err != nil {
        return err
    }
    
    // Print summary
    fmt.Printf("\n📊 Processing Summary:\n")
    fmt.Printf("   Regular DOCs: %d\n", len(docs))
    fmt.Printf("   Shard files: %d (from %d large files)\n", len(shardFiles), shardedCount)
    fmt.Printf("   Compressed files: %d\n", compressedCount)
    fmt.Printf("   Size reduction: %.2fKB -> %.2fKB (%.1f%%)\n",
        totalOriginalSize, totalProcessedSize,
        (1-totalProcessedSize/totalOriginalSize)*100)
    
    // Show deployment plan
    fmt.Printf("\n🚀 Deployment Plan:\n")
    fmt.Printf("   1. Deploy %d regular DOCs\n", len(docs))
    if len(shardFiles) > 0 {
        fmt.Printf("   2. Deploy %d shard files as DOCs with .shard tag\n", len(shardFiles))
        fmt.Printf("   3. Create INDEX with .shards tag for reconstruction\n")
    } else {
        fmt.Printf("   2. Create INDEX with all DOC SCIDs\n")
    }
    
    return nil
}
 
func main() {
    if len(os.Args) < 2 {
        fmt.Println("Usage: process-tela-files <directory>")
        os.Exit(1)
    }
    
    dirPath := os.Args[1]
    
    if err := processDirectoryForTELA(dirPath); err != nil {
        fmt.Printf("Processing failed: %v\n", err)
        os.Exit(1)
    }
    
    fmt.Println("\n✅ Processing complete!")
    fmt.Println("💡 Next steps:")
    fmt.Println("   1. Review the processed files")
    fmt.Println("   2. Deploy DOCs using tela.Installer()")
    fmt.Println("   3. Create INDEX with DOC SCIDs")
    fmt.Println("   4. Test the deployed application")
}

Key Takeaways

Example Patterns

  • Always validate inputs and handle errors gracefully
  • Use compression and sharding for large files
  • Implement caching for better performance
  • Provide comprehensive user feedback
  • Structure code for maintainability and reuse

These examples demonstrate:

  1. Complete Workflows: Full application deployment from files to running servers
  2. Error Handling: Robust error handling and user feedback
  3. Performance Optimization: Caching, compression, and efficient resource usage
  4. Real-world Integration: Web services, APIs, and user interfaces
  5. Best Practices: Code organization, validation, and maintenance patterns

Use these examples as templates for building your own TELA applications and services. Each example can be adapted and extended for specific use cases while maintaining the core principles of the TELA ecosystem.