api

package
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 14, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package api provides middleware for authentication and rate limiting

Package api provides HTTP REST API handlers for ZenLive

Package api provides REST API server for room management

Package api provides JWT token generation for room access

Package api provides WebSocket signaling for room operations

Index

Constants

View Source
const (
	MsgJoinRoom         = "join_room"
	MsgLeaveRoom        = "leave_room"
	MsgPublishTrack     = "publish_track"
	MsgUnpublishTrack   = "unpublish_track"
	MsgSubscribeTrack   = "subscribe_track"
	MsgUnsubscribeTrack = "unsubscribe_track"
	MsgUpdateMetadata   = "update_metadata"
	MsgSendData         = "send_data"
	MsgRoomEvent        = "room_event"
	MsgError            = "error"
	MsgPing             = "ping"
	MsgPong             = "pong"
)

WebSocket message types

Variables

This section is empty.

Functions

func GetClaims

func GetClaims(r *http.Request) (*auth.TokenClaims, bool)

GetClaims extracts claims from request context

Types

type AddParticipantRequest

type AddParticipantRequest struct {
	ParticipantID string                 `json:"participant_id"`
	UserID        string                 `json:"user_id"`
	Username      string                 `json:"username"`
	Role          string                 `json:"role,omitempty"`
	Metadata      map[string]interface{} `json:"metadata,omitempty"`
}

AddParticipantRequest represents a request to add a participant

type AuthMiddleware

type AuthMiddleware struct {
	// contains filtered or unexported fields
}

AuthMiddleware provides JWT authentication middleware

func NewAuthMiddleware

func NewAuthMiddleware(jwtAuth *auth.JWTAuthenticator, log logger.Logger) *AuthMiddleware

NewAuthMiddleware creates a new auth middleware

func (*AuthMiddleware) Authenticate

func (m *AuthMiddleware) Authenticate(next http.HandlerFunc) http.HandlerFunc

Authenticate validates JWT tokens from Authorization header

type CORSMiddleware

type CORSMiddleware struct {
	// contains filtered or unexported fields
}

CORS middleware for cross-origin requests

func NewCORSMiddleware

func NewCORSMiddleware(origins, methods, headers []string) *CORSMiddleware

NewCORSMiddleware creates a new CORS middleware

func (*CORSMiddleware) Handle

func (cm *CORSMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc

Handle applies CORS headers

type Config

type Config struct {
	Addr         string
	JWTSecret    string // JWT secret for token generation
	RateLimitRPM int    // Requests per minute
	CORSOrigins  []string
	CORSMethods  []string
	CORSHeaders  []string
}

Config contains server configuration

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns default server configuration

type ContextKey

type ContextKey string

ContextKey is a custom type for context keys

const (
	// ContextKeyClaims is the key for storing claims in context
	ContextKeyClaims ContextKey = "claims"
)

type CreateRoomRequest

type CreateRoomRequest struct {
	Name            string                 `json:"name"`
	MaxParticipants int                    `json:"max_participants,omitempty"`
	EmptyTimeout    int                    `json:"empty_timeout,omitempty"` // seconds
	Metadata        map[string]interface{} `json:"metadata,omitempty"`
	CreatedBy       string                 `json:"created_by"`
}

CreateRoomRequest represents a request to create a room

type DataMessage

type DataMessage struct {
	From    string `json:"from"`
	To      string `json:"to,omitempty"` // Empty = broadcast
	Topic   string `json:"topic"`
	Payload []byte `json:"payload"`
}

DataMessage represents a data channel message

type ErrorResponse

type ErrorResponse struct {
	Error   string `json:"error"`
	Code    int    `json:"code"`
	Message string `json:"message"`
}

ErrorResponse represents an error response

type GenerateTokenRequest

type GenerateTokenRequest struct {
	RoomID      string                      `json:"room_id"`
	UserID      string                      `json:"user_id"`
	Username    string                      `json:"username"`
	Permissions room.ParticipantPermissions `json:"permissions,omitempty"`
	TTL         int                         `json:"ttl,omitempty"` // seconds, default 24h
	Metadata    map[string]interface{}      `json:"metadata,omitempty"`
}

GenerateTokenRequest represents a request to generate an access token

type JoinRoomData

type JoinRoomData struct {
	RoomID string `json:"room_id"`
	Token  string `json:"token"`
	UserID string `json:"user_id"`
}

JoinRoomData represents join room message data

type ParticipantResponse

type ParticipantResponse struct {
	ID       string                 `json:"id"`
	UserID   string                 `json:"user_id"`
	Username string                 `json:"username"`
	JoinedAt time.Time              `json:"joined_at"`
	Role     string                 `json:"role"`
	State    string                 `json:"state"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

ParticipantResponse represents a participant in API responses

type PublishTrackData

type PublishTrackData struct {
	TrackID   string `json:"track_id"`
	Kind      string `json:"kind"` // "audio" or "video"
	Label     string `json:"label,omitempty"`
	Simulcast bool   `json:"simulcast,omitempty"`
}

PublishTrackData represents publish track message data

type RateLimiter

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter provides rate limiting middleware

func NewRateLimiter

func NewRateLimiter(requestsPerMinute int, log logger.Logger) *RateLimiter

NewRateLimiter creates a new rate limiter

func (*RateLimiter) Limit

func (rl *RateLimiter) Limit(next http.HandlerFunc) http.HandlerFunc

Limit applies rate limiting based on client IP

type RoomEventData

type RoomEventData struct {
	EventType string      `json:"event_type"`
	Data      interface{} `json:"data"`
	Timestamp time.Time   `json:"timestamp"`
}

RoomEventData represents room event data

type RoomHandler

type RoomHandler struct {
	// contains filtered or unexported fields
}

RoomHandler handles HTTP requests for room management

func NewRoomHandler

func NewRoomHandler(roomManager *room.RoomManager, log logger.Logger) *RoomHandler

NewRoomHandler creates a new room HTTP handler

func (*RoomHandler) AddParticipant

func (h *RoomHandler) AddParticipant(w http.ResponseWriter, r *http.Request)

AddParticipant handles POST /api/rooms/:roomId/participants

func (*RoomHandler) CreateRoom

func (h *RoomHandler) CreateRoom(w http.ResponseWriter, r *http.Request)

CreateRoom handles POST /api/rooms

func (*RoomHandler) DeleteRoom

func (h *RoomHandler) DeleteRoom(w http.ResponseWriter, r *http.Request)

DeleteRoom handles DELETE /api/rooms/:roomId

func (*RoomHandler) GetRoom

func (h *RoomHandler) GetRoom(w http.ResponseWriter, r *http.Request)

GetRoom handles GET /api/rooms/:roomId

func (*RoomHandler) ListParticipants

func (h *RoomHandler) ListParticipants(w http.ResponseWriter, r *http.Request)

ListParticipants handles GET /api/rooms/:roomId/participants

func (*RoomHandler) ListRooms

func (h *RoomHandler) ListRooms(w http.ResponseWriter, r *http.Request)

ListRooms handles GET /api/rooms

func (*RoomHandler) RemoveParticipant

func (h *RoomHandler) RemoveParticipant(w http.ResponseWriter, r *http.Request)

RemoveParticipant handles DELETE /api/rooms/:roomId/participants/:participantId

type RoomResponse

type RoomResponse struct {
	ID               string                 `json:"id"`
	Name             string                 `json:"name"`
	CreatedAt        time.Time              `json:"created_at"`
	CreatedBy        string                 `json:"created_by"`
	MaxParticipants  int                    `json:"max_participants"`
	ParticipantCount int                    `json:"participant_count"`
	Metadata         map[string]interface{} `json:"metadata,omitempty"`
}

RoomResponse represents a room in API responses

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server represents the REST API server

func NewServer

func NewServer(
	roomManager *room.RoomManager,
	jwtAuth *auth.JWTAuthenticator,
	config *Config,
	log logger.Logger,
) *Server

NewServer creates a new API server

func (*Server) Start

func (s *Server) Start() error

Start starts the API server

type SignalingServer

type SignalingServer struct {
	// contains filtered or unexported fields
}

SignalingServer handles WebSocket connections for room signaling

func NewSignalingServer

func NewSignalingServer(roomManager *room.RoomManager, log logger.Logger) *SignalingServer

NewSignalingServer creates a new signaling server

func (*SignalingServer) BroadcastToRoom

func (s *SignalingServer) BroadcastToRoom(roomID string, msg *WSMessage, excludeClientID string)

BroadcastToRoom broadcasts a message to all clients in a room

func (*SignalingServer) HandleWebSocket

func (s *SignalingServer) HandleWebSocket(w http.ResponseWriter, r *http.Request)

HandleWebSocket handles WebSocket connection requests

func (*SignalingServer) SendToParticipant

func (s *SignalingServer) SendToParticipant(roomID, participantID string, msg *WSMessage)

SendToParticipant sends a message to a specific participant

type SubscribeTrackData

type SubscribeTrackData struct {
	ParticipantID string `json:"participant_id"`
	TrackID       string `json:"track_id"`
	Quality       string `json:"quality,omitempty"` // "high", "medium", "low"
}

SubscribeTrackData represents subscribe track message data

type TokenHandler

type TokenHandler struct {
	// contains filtered or unexported fields
}

TokenHandler handles token generation for room access

func NewTokenHandler

func NewTokenHandler(roomManager *room.RoomManager, jwtAuth *auth.JWTAuthenticator, jwtSecret string, log logger.Logger) *TokenHandler

NewTokenHandler creates a new token handler

func (*TokenHandler) GenerateAccessToken

func (h *TokenHandler) GenerateAccessToken(w http.ResponseWriter, r *http.Request)

GenerateAccessToken handles POST /api/rooms/:roomId/tokens

type TokenResponse

type TokenResponse struct {
	Token     string    `json:"token"`
	ExpiresAt time.Time `json:"expires_at"`
	RoomID    string    `json:"room_id"`
	UserID    string    `json:"user_id"`
}

TokenResponse represents a token response

type UpdateMetadataData

type UpdateMetadataData struct {
	Metadata map[string]interface{} `json:"metadata"`
}

UpdateMetadataData represents update metadata message data

type WSClient

type WSClient struct {
	// contains filtered or unexported fields
}

WSClient represents a WebSocket client connection

type WSMessage

type WSMessage struct {
	Type   string          `json:"type"`
	RoomID string          `json:"room_id,omitempty"`
	Data   json.RawMessage `json:"data,omitempty"`
}

WSMessage represents a WebSocket message

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL