Skip to content

Server SDK (Go) API reference

This page lists the primary public APIs used by a custom RTC service. Source under tirtc-service-sdk/pkg is authoritative. See the tirtcxauth authentication specification for the signing algorithm.

API list

PackageAPIPurpose
tirtcxInit / StartInitialize and start the process-wide TiRTC engine
tirtcxStop / UninitStop and release the process-wide TiRTC engine
tirtcxSetNativeLogLevelSet the TiRTC C library log level
tirtcxGetVersionReturn the TiRTC C library version
tirtcxauthNewEd25519TokenIssuerCreate a token issuer
tirtcxauthNewEd25519TokenVerifierCreate a token verifier
tirtcxauthBearerInterceptorCreate HTTP bearer authentication
tirtcxauthClaimsFromContextRead verified claims from a request
tirtcxNewWhipAcceptorCreate an authentication-independent acceptor
tirtcxWhipAcceptor.WhipAcceptAccept an SDP Offer and create a WHIP Session
tirtcxWhipSessionOwn a pending or connected session
tirtcxConnAn established TiRTC connection object. Handles media exchange, commands, and connection events.
whipechoNewHTTPAdapterCreate an embeddable Echo adapter

SDK lifecycle

go
func Init() error
func Start(ctx context.Context) error
func Stop()
func Uninit()
func SetNativeLogLevel(level int)
func GetVersion() string

Initialize one TiRTC engine per process:

  1. If needed, call SetNativeLogLevel before initialization.
  2. Call Init successfully before using other tirtcx APIs.
  3. Call Start(ctx) and wait for the system-started event. ctx must not be nil; a timeout or cancellation returns the corresponding context error.
  4. During shutdown, close business sessions, then call Stop followed by Uninit.

GetVersion returns the loaded TiRTC C library version for startup logs and diagnostics.

Token and HTTP authentication

BearerInterceptor

go
func BearerInterceptor(
    service string,
    verifier TokenVerifier,
    observers ...AuthObserver,
) HTTPInterceptor

BearerInterceptor verifies the bearer token against the complete raw query. It returns 401 for a missing token, 403 for an invalid token, and 500 for invalid configuration. On success it places a copy of TokenClaims in the request context.

Read the verified identity with:

go
claims, ok := tirtcxauth.ClaimsFromContext(r.Context())
TokenClaims fieldMeaning
SubjectDelegated device ID
ScopeAccess scope bound to the service and canonical query
IssuerCustom RTC Key ID that issued the token
IssuedAt / ExpiresAtIssue and expiry time in Unix seconds

The token can be reused until exp, and tirtcxauth does not perform replay checks. The device SDK automatically protects the complete TiRtcWhipConnect call against replay. To reject direct replay of requests to the custom RTC service, add a one-time business parameter to the peer_id query and have the custom RTC service consume it on first use.

Use this interceptor for the resource-creation POST, not for DELETE <Location>.

Token issuing

Issue tokens with:

go
issuer, err := tirtcxauth.NewEd25519TokenIssuer(privateKeys)
token, err := issuer.Issue(service, customRtcKeyID, deviceID, rawQuery, ttl)

The SDK canonicalizes the peer_id query for signing.

WHIP accept

NewWhipAcceptor

go
acceptor := tirtcx.NewWhipAcceptor(candidate)

An empty candidate uses the SDK default address. Set it only when the service must advertise another reachable public address.

WhipAcceptor.WhipAccept

go
session, err := acceptor.WhipAccept(ctx, offer, eventOptions)

The context passed to WhipAccept controls only the synchronous SDP Answer phase. Authentication must happen before this call.

Applications own resource IDs, Location, registries, and DELETE policy.

Session lifecycle

MethodBehavior
AnswerSDP()Return a copy of the SDP Answer for the HTTP 201 response
WaitConn(ctx)Wait for the final connection result; safe for concurrent and repeated calls
Close()Idempotently terminate a pending or connected session

Each WaitConn caller has an independent context. Canceling one waiter does not close the session.

Connection API

MethodPurpose
Events()Return enabled event channels
Done()Close on normal disconnect or terminal error
Err()Return the terminal error after Done; normal disconnect returns nil
EventStats()Return cumulative event-drop counts
SendAudio, SendVideo, SendMessage, SendCommandSend data
Subscription and key-frame methodsControl media streams
Close()Disconnect

FrameInfo and media types

go
type FrameInfo struct {
    StreamID uint8
    Media    MediaType
    Flags    uint8
    Ts       uint32
    Length   uint32
}
FieldMeaning
StreamID015; globally unique within a connection, so audio and video cannot reuse an ID
MediaFrame encoding listed below
FlagsFor audio: 0=8 kHz/16-bit/mono, 1=16 kHz/16-bit/mono, 2=8 kHz/16-bit/stereo, 3=16 kHz/16-bit/stereo. For video, bit 0 marks a key frame
TsA 32-bit millisecond timestamp; keep it monotonic within a stream and allow natural wraparound
LengthReceived payload length. Send methods derive it from data; callers need not set it
ConstantPayload
MediaMessageIn-stream message
AudioPCM / AudioALaw / AudioAAC / AudioOpus / AudioAMRAudio frame in the named encoding
VideoJPEG / VideoH264 / VideoH265Video frame in the named encoding

SendAudio, SendVideo, and SendMessage copy the payload before returning, so the input slice may be reused afterward. Received event payloads are Go-owned and remain readable after the native callback returns. Agree on exact codec parameters with the device implementation.

ConnEventOptions

ConnEventOptions configures the buffer capacity of each connection event channel and the synchronous handlers for remote subscription requests.

FieldConfiguration
AudioBuffer / VideoBuffer / MessageBuffer / CommandBufferBuffer capacity of the corresponding data event channel
ErrorBuffer / DisconnectedBufferBuffer capacity of the connection error and disconnect event channels
RequestKeyFrameBufferBuffer capacity of the key-frame request event channel
UnsubscribeVideoBuffer / UnsubscribeAudioBufferBuffer capacity of the unsubscribe event channels
SubscribeVideoHandler / SubscribeAudioHandlerSynchronous handlers for remote subscription requests

Each *Buffer value is the maximum number of events that the corresponding event channel can buffer. A non-positive value disables the event. A positive value below MinEventBufferSize is raised to that minimum. A subscription handler returns 0 to accept and a non-zero value to reject. It runs in a native callback and must return quickly; a missing handler or panic defaults to 0.

Echo HTTP API

go
echo, err := whipecho.NewHTTPAdapter(
    acceptor,
    "/whip/echo/resource",
    whipecho.HTTPOptions{},
)

The location prefix must be a canonical absolute path without a trailing slash.

HTTPOptions configures the SDP size limit, connection timeout, logger, and observer.

MethodPurpose
Wrap(business)Add Echo selection before a business handler
PostHandler()Return a dedicated Echo POST handler
TryHandlePOST(w, r)Framework-neutral Echo selection
DeleteHandler()Return a standard-library DELETE handler
ServeDelete(w, r, id)Delete using an ID extracted by another router
Stats()Return a thread-safe statistics snapshot
Shutdown(ctx)Reject new sessions, close active sessions, and wait

TiRTC