Skip to content

Go API

This page lists the primary public APIs used by a WHIP Service. Source under whip-sdk/go/pkg is authoritative.

API list

PackageAPIPurpose
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

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
IssuerAccess Key ID that issued the token
IssuedAt / ExpiresAtIssue and expiry time in Unix seconds

The token contains no nonce, and the verifier performs no replay check. The TiRTC SDK and platform provide per-request connection protection automatically.

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, accessKey, 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

FieldEvent
AudioBuffer / VideoBuffer / MessageBuffer / CommandBufferCorresponding data event
ErrorBuffer / DisconnectedBufferConnection error and disconnect
RequestKeyFrameBufferKey-frame request
UnsubscribeVideoBuffer / UnsubscribeAudioBufferUnsubscribe event
SubscribeVideoHandler / SubscribeAudioHandlerSynchronous decision for a remote subscription request

A non-positive buffer 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 WHIP