Skip to content

Example Bridge Implementation for TON Protocol

Oleksii Bondarenko edited this page Oct 12, 2024 · 1 revision
package main

import (
    "encoding/base64"
    "encoding/json"
    "fmt"
    "net/http"
    "time"
)

type BridgeMessage struct {
    From    string `json:"from"`
    Message string `json:"message"`
}

var messageQueue = make(map[string][]BridgeMessage)

func main() {
    http.HandleFunc("/events", handleEvents)
    http.HandleFunc("/message", handleMessage)
    fmt.Println("Bridge server is running on port 8080")
    http.ListenAndServe(":8080", nil)
}

func handleEvents(w http.ResponseWriter, r *http.Request) {
    clientID := r.URL.Query().Get("client_id")
    if clientID == "" {
        http.Error(w, "client_id is required", http.StatusBadRequest)
        return
    }

    w.Header().Set("Content-Type", "text/event-stream")
    w.Header().Set("Cache-Control", "no-cache")
    w.Header().Set("Connection", "keep-alive")

    for {
        if messages, ok := messageQueue[clientID]; ok && len(messages) > 0 {
            for _, msg := range messages {
                fmt.Fprintf(w, "data: %s\n\n", toJSON(msg))
            }
            messageQueue[clientID] = nil
        }
        fmt.Fprintf(w, "data: heartbeat\n\n")
        w.(http.Flusher).Flush()
        time.Sleep(10 * time.Second)
    }
}

func handleMessage(w http.ResponseWriter, r *http.Request) {
    clientID := r.URL.Query().Get("client_id")
    to := r.URL.Query().Get("to")
    ttl := r.URL.Query().Get("ttl")
    topic := r.URL.Query().Get("topic")

    if clientID == "" || to == "" {
        http.Error(w, "client_id and to are required", http.StatusBadRequest)
        return
    }

    var msg BridgeMessage
    err := json.NewDecoder(r.Body).Decode(&msg)
    if err != nil {
        http.Error(w, "invalid message format", http.StatusBadRequest)
        return
    }

    msg.From = clientID
    messageQueue[to] = append(messageQueue[to], msg)

    w.WriteHeader(http.StatusOK)
}

func toJSON(v interface{}) string {
    data, _ := json.Marshal(v)
    return string(data)
}

Explanation

  • Event Handling:
    • The handleEvents function listens for incoming requests from clients (apps or wallets) and sends messages from the queue to the client.
  • Message Handling:
    • The handleMessage function receives messages from clients and adds them to the message queue for the intended recipient.
  • Heartbeat:
    • The server sends a “heartbeat” message periodically to keep the connection alive.

This is a basic example to illustrate the concept. In a real-world implementation, you would need to handle security, error handling, and other considerations more robustly.

READ MORE on TON official repository

Clone this wiki locally