### Clone and Run Project Locally (Bash)
Source: https://github.com/matrixseven/file-transfer-go/blob/main/chuan-next/README.md
This snippet demonstrates how to clone the project repository, navigate into the project directory, and start the backend and frontend development servers. It assumes you have Git, Go, and Node.js installed.
```bash
git clone https://github.com/MatrixSeven/file-transfer-go.git
cd file-transfer-go
# 启动后端服务
make dev
# 启动前端服务
cd chuan-next
npm install
npm run dev
```
--------------------------------
### Local Build and Run File Transfer Go
Source: https://context7.com/matrixseven/file-transfer-go/llms.txt
Steps to clone the File Transfer Go repository, build the full-stack application using the provided script, and run the compiled executable. It also outlines the setup for development mode, running backend and frontend servers separately.
```bash
# Clone repository
git clone https://github.com/MatrixSeven/file-transfer-go.git
cd file-transfer-go
# Build full-stack application
./build-fullstack.sh
# Run the application
./dist/file-transfer-go
# Access at http://localhost:8080
```
```bash
# Development mode setup
# Terminal 1 - Backend
make dev
# Terminal 2 - Frontend
cd chuan-next
yarn install
yarn dev
# Frontend dev server: http://localhost:3000
# Backend server: http://localhost:8080
```
--------------------------------
### WebRTC ICE Server Configuration in TypeScript
Source: https://context7.com/matrixseven/file-transfer-go/llms.txt
Example of configuring custom STUN/TURN servers for WebRTC using TypeScript in the frontend application. This is useful for NAT traversal in restricted network environments.
```typescript
// Frontend ICE configuration - CHUAN-NEXT/src/hooks/settings/useIceServersConfig.ts
import { useIceServersConfig } from '@/hooks/settings';
function SettingsComponent() {
const { iceServers, updateIceServers } = useIceServersConfig();
// Configure custom TURN server
const customConfig = {
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' },
{
urls: 'turn:your-turn-server.com:3478',
username: 'your-username',
credential: 'your-password'
}
]
};
updateIceServers(customConfig.iceServers);
return (
Current ICE Servers:
{iceServers.map((server, idx) => (
{server.urls}
))}
);
}
```
--------------------------------
### Deploy Project with Docker Compose (Bash)
Source: https://github.com/matrixseven/file-transfer-go/blob/main/chuan-next/README.md
This snippet shows how to deploy the entire application, including backend and frontend services, using Docker Compose. It starts all services in detached mode and provides the URL to access the application.
```bash
# 一键启动所有服务
docker-compose up -d
# 访问应用
open http://localhost:8080
```
--------------------------------
### GET /api/ws/webrtc
Source: https://context7.com/matrixseven/file-transfer-go/llms.txt
Establishes a WebSocket connection for WebRTC signaling, enabling P2P communication setup.
```APIDOC
## GET /api/ws/webrtc
### Description
Establishes a WebSocket connection for WebRTC signaling between peers. This connection is crucial for exchanging connection information needed to set up direct P2P data channels.
### Method
GET
### Endpoint
/api/ws/webrtc
### Parameters
#### Query Parameters
- **code** (string) - Required - The 6-character pickup code of the room for the signaling connection.
- **role** (string) - Required - The role of the client establishing the connection ('sender' or 'receiver').
### Request Example
```bash
# Example connection as sender
ws://localhost:8080/api/ws/webrtc?code=A3K7M9&role=sender
# Example connection as receiver
ws://localhost:8080/api/ws/webrtc?code=A3K7M9&role=receiver
```
### Response
(WebSocket connection establishment - no traditional HTTP response body)
### Notes
This endpoint is for establishing a WebSocket connection. Client-side code will manage the WebSocket lifecycle and handle signaling messages exchanged over this connection.
```
--------------------------------
### URL Parameters for Specific Features (URL)
Source: https://github.com/matrixseven/file-transfer-go/blob/main/chuan-next/README.md
This snippet illustrates how to use URL parameters to directly access specific features of the application. It shows examples for file transfer (send), text transfer (receive), and desktop sharing (send).
```url
/?type=file&mode=send
/?type=text&mode=receive
/?type=desktop&mode=send
```
--------------------------------
### Check Room Status API - cURL Example
Source: https://context7.com/matrixseven/file-transfer-go/llms.txt
This cURL command demonstrates how to check the current status of a transfer room, including participant online status and room capacity. It requires the room code as a query parameter.
```bash
# Check room status
curl -X GET "http://localhost:8080/api/room-info?code=A3K7M9"
```
--------------------------------
### GET /api/room-info
Source: https://context7.com/matrixseven/file-transfer-go/llms.txt
Retrieves the current status of a transfer room, including participant availability and room capacity.
```APIDOC
## GET /api/room-info
### Description
Retrieves the current status of a transfer room, including online participants and whether the room is full.
### Method
GET
### Endpoint
/api/room-info
### Parameters
#### Query Parameters
- **code** (string) - Required - The 6-character pickup code of the room to check.
### Request Example
```bash
curl -X GET "http://localhost:8080/api/room-info?code=A3K7M9"
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the request was successful.
- **exists** (boolean) - True if the room with the given code exists, false otherwise.
- **sender_online** (boolean) - True if the sender is currently online in the room.
- **receiver_online** (boolean) - True if the receiver is currently online in the room.
- **is_room_full** (boolean) - True if the room has reached its maximum capacity.
- **created_at** (string) - The timestamp when the room was created (ISO 8601 format).
#### Response Example
```json
{
"success": true,
"exists": true,
"sender_online": true,
"receiver_online": false,
"is_room_full": false,
"created_at": "2025-10-21T10:30:00Z"
}
```
```
--------------------------------
### Docker Deployment for File Transfer Go
Source: https://context7.com/matrixseven/file-transfer-go/llms.txt
Instructions for deploying the File Transfer Go application using Docker, including options for Docker Compose and direct Docker commands. It also shows how to set custom environment variables for production deployments.
```bash
# Using Docker Compose (recommended)
docker-compose up -d
# Using Docker directly
docker run -d \
-p 8080:8080 \
--name file-transfer-go \
matrixseven/file-transfer-go:latest
# Custom environment variables
docker run -d \
-p 8080:8080 \
-e NODE_ENV=production \
-e PORT=8080 \
--restart unless-stopped \
--name file-transfer-go \
matrixseven/file-transfer-go:latest
```
```yaml
# docker-compose.yml example
version: '3.8'
services:
file-transfer:
image: matrixseven/file-transfer-go:latest
ports:
- "8080:8080"
environment:
- NODE_ENV=production
- PORT=8080
restart: unless-stopped
container_name: file-transfer-go
```
--------------------------------
### POST /api/create-room
Source: https://context7.com/matrixseven/file-transfer-go/llms.txt
Creates a new transfer room and returns a unique 6-character pickup code for users to join.
```APIDOC
## POST /api/create-room
### Description
Creates a new transfer room and returns a unique 6-character pickup code. The code uses only uppercase letters and numbers, excluding confusing characters like '0' and 'O'.
### Method
POST
### Endpoint
/api/create-room
### Parameters
#### Request Body
- **{}** (object) - No specific fields required, an empty JSON object is expected.
### Request Example
```json
{
"": ""
}
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the room creation was successful.
- **code** (string) - The unique 6-character pickup code for the newly created room.
- **message** (string) - A confirmation message, e.g., "房间创建成功".
#### Response Example
```json
{
"success": true,
"code": "A3K7M9",
"message": "房间创建成功"
}
```
```
--------------------------------
### WebRTC WebSocket Signaling Connection - Frontend
Source: https://context7.com/matrixseven/file-transfer-go/llms.txt
This React component with a custom hook demonstrates how to establish a WebRTC connection to a room using the provided room code and role. It manages connection state and provides feedback.
```typescript
// Frontend WebRTC connection - chuan-next/src/hooks/connection/useSharedWebRTCManager.ts
import { useSharedWebRTCManager } from '@/hooks/connection';
function FileTransferComponent() {
const connection = useSharedWebRTCManager();
async function connectToRoom(roomCode: string) {
try {
await connection.connect(roomCode, 'sender');
console.log('Connected:', connection.isConnected);
console.log('Peer connected:', connection.isPeerConnected);
} catch (error) {
console.error('Connection failed:', error);
}
}
return (
);
}
```
--------------------------------
### Create Transfer Room API - Go Backend
Source: https://context7.com/matrixseven/file-transfer-go/llms.txt
This Go backend handler creates a new transfer room and returns a unique 6-character pickup code. It is designed to be called via HTTP POST requests.
```go
// Backend Handler - cmd/router.go and internal/handlers/handlers.go
r.Post("/api/create-room", h.CreateRoomHandler)
```
--------------------------------
### WebRTC WebSocket Signaling Connection - Go Backend
Source: https://context7.com/matrixseven/file-transfer-go/llms.txt
This Go backend handler is responsible for establishing WebSocket connections for WebRTC signaling. It requires the room code and the role (sender/receiver) as query parameters.
```go
// Backend WebSocket Handler - internal/services/webrtc_service.go
r.Get("/api/ws/webrtc", h.HandleWebRTCWebSocket)
// Connection parameters:
// - code: Room code (6 characters)
// - role: "sender" or "receiver"
```
--------------------------------
### Create Transfer Room API - Frontend Client
Source: https://context7.com/matrixseven/file-transfer-go/llms.txt
This TypeScript function in the frontend client makes an API call to create a new transfer room. It handles the response and logs the room code or any errors.
```typescript
// Frontend Client API - chuan-next/src/lib/client-api.ts
import { clientAPI } from './client-api';
async function createTransferRoom() {
try {
const response = await clientAPI.createRoom();
if (response.success) {
console.log('Room code:', response.data.code);
return response.data.code;
}
} catch (error) {
console.error('Failed to create room:', error);
}
}
```
--------------------------------
### Receive Text Over WebRTC DataChannel for Real-time Sync
Source: https://context7.com/matrixseven/file-transfer-go/llms.txt
Facilitates real-time text synchronization by receiving text updates and typing status indicators over a WebRTC DataChannel. It connects as a receiver and registers callbacks to update the UI with the incoming text and display typing indicators.
```typescript
// Text receiver example
function TextReceiverComponent() {
const connection = useSharedWebRTCManager();
const textTransfer = useTextTransferBusiness(connection);
const [receivedText, setReceivedText] = useState('');
useEffect(() => {
connection.connect('A3K7M9', 'receiver');
// Register text sync callback
const unregisterText = textTransfer.onTextSync((text) => {
setReceivedText(text);
console.log('Received text update:', text.length, 'characters');
});
// Register typing status callback
const unregisterTyping = textTransfer.onTypingStatus((isTyping) => {
console.log('Sender is typing:', isTyping);
});
return () => {
unregisterText();
unregisterTyping();
};
}, []);
return (
Received Text:
{receivedText}
{textTransfer.isTyping &&
Sender is typing...
}
);
}
```
--------------------------------
### Send Text Over WebRTC DataChannel for Real-time Sync
Source: https://context7.com/matrixseven/file-transfer-go/llms.txt
Implements real-time text synchronization over WebRTC. This sender component establishes a connection, sends text updates as the user types, and also transmits typing status indicators. It uses a timeout to determine when the user stops typing.
```typescript
// Text transfer business logic - chuan-next/src/hooks/text-transfer/useTextTransferBusiness.ts
import { useSharedWebRTCManager } from '@/hooks/connection';
import { useTextTransferBusiness } from '@/hooks/text-transfer';
function TextSenderComponent() {
const connection = useSharedWebRTCManager();
const textTransfer = useTextTransferBusiness(connection);
const [text, setText] = useState('');
const [typingTimeout, setTypingTimeout] = useState();
useEffect(() => {
connection.connect('A3K7M9', 'sender');
}, []);
const handleTextChange = (newText: string) => {
setText(newText);
// Send typing status
textTransfer.sendTypingStatus(true);
// Send text sync
textTransfer.sendTextSync(newText);
// Clear previous timeout
if (typingTimeout) clearTimeout(typingTimeout);
// Set typing to false after 1 second of no input
const timeout = setTimeout(() => {
textTransfer.sendTypingStatus(false);
}, 1000);
setTypingTimeout(timeout);
};
return (
);
}
```
--------------------------------
### Check Room Status API - Frontend Usage
Source: https://context7.com/matrixseven/file-transfer-go/llms.txt
This TypeScript snippet shows how to use the frontend client API to retrieve the status of a WebRTC transfer room. It checks for room existence and participant online status.
```typescript
// Frontend usage
const response = await clientAPI.getWebRTCRoomStatus('A3K7M9');
if (response.success && response.data.exists) {
console.log('Sender online:', response.data.sender_online);
console.log('Receiver online:', response.data.receiver_online);
}
```
--------------------------------
### Receive File Over WebRTC DataChannel
Source: https://context7.com/matrixseven/file-transfer-go/llms.txt
Manages receiving files over a WebRTC DataChannel. It connects as a receiver, registers a callback for incoming files, and automatically initiates a download for each received file. The function also updates the UI with received file information and progress.
```typescript
// File receiver example
function FileReceiverComponent() {
const connection = useSharedWebRTCManager();
const fileTransfer = useFileTransferBusiness(connection);
const [receivedFiles, setReceivedFiles] = useState([]);
useEffect(() => {
// Connect as receiver
connection.connect('A3K7M9', 'receiver');
// Register file received callback
const unregister = fileTransfer.onFileReceived((fileData) => {
console.log('Received file:', fileData.file.name);
setReceivedFiles(prev => [...prev, fileData.file]);
// Download file automatically
const url = URL.createObjectURL(fileData.file);
const a = document.createElement('a');
a.href = url;
a.download = fileData.file.name;
a.click();
URL.revokeObjectURL(url);
});
return unregister;
}, []);
return (
Received Files:
{receivedFiles.map((file, idx) => (
{file.name} ({file.size} bytes)
))}
Progress: {fileTransfer.progress}%
);
}
```
--------------------------------
### Send File Over WebRTC DataChannel with ACK
Source: https://context7.com/matrixseven/file-transfer-go/llms.txt
Handles file uploading via WebRTC DataChannel using chunk-based transfer and an ACK mechanism for reliability. It includes progress tracking and automatic retry capabilities. This function requires a connected WebRTC connection and registers a progress callback before sending the file.
```typescript
import { useSharedWebRTCManager } from '@/hooks/connection';
import { useFileTransferBusiness } from '@/hooks/file-transfer';
function FileSenderComponent() {
const connection = useSharedWebRTCManager();
const fileTransfer = useFileTransferBusiness(connection);
// Send file with progress tracking
async function handleFileUpload(file: File) {
try {
await connection.connect('A3K7M9', 'sender');
// Register progress callback
fileTransfer.onFileProgress((progress) => {
console.log(`Progress: ${progress.progress}% for ${progress.fileName}`);
});
// Send file (256KB chunks with CRC32 checksum)
await fileTransfer.sendFile(file);
console.log('File sent successfully');
} catch (error) {
console.error('File transfer failed:', error);
}
}
return (
{
if (e.target.files?.[0]) handleFileUpload(e.target.files[0]);
}} />
);
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.