feat:环境变量处理

This commit is contained in:
MatrixSeven
2025-08-01 19:38:59 +08:00
parent 664fe2fdaa
commit dbfdbf0116
15 changed files with 396 additions and 1035 deletions

View File

@@ -3,6 +3,8 @@
import { useState, useEffect, useCallback } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import Hero from '@/components/Hero';
import FileTransfer from '@/components/FileTransfer';
import TextTransfer from '@/components/TextTransfer';
@@ -31,6 +33,10 @@ export default function HomePage() {
// URL参数管理
const [activeTab, setActiveTab] = useState<'file' | 'text' | 'desktop'>('file');
// 确认对话框状态
const [showConfirmDialog, setShowConfirmDialog] = useState(false);
const [pendingTabSwitch, setPendingTabSwitch] = useState<string>('');
// 从URL参数中获取初始状态
useEffect(() => {
const type = searchParams.get('type') as 'file' | 'text' | 'desktop';
@@ -81,49 +87,37 @@ export default function HomePage() {
const hasActiveConnection = isConnected || pickupCode || isConnecting;
if (hasActiveConnection && value !== activeTab) {
// 如果已有活跃连接且要切换到不同的tab在新窗口打开
const currentUrl = window.location.origin + window.location.pathname;
const newUrl = `${currentUrl}?type=${value}`;
// 在新标签页打开
window.open(newUrl, '_blank');
// 给出提示
let currentMode = '';
let targetMode = '';
switch (activeTab) {
case 'file':
currentMode = '文件传输';
break;
case 'text':
currentMode = '文字传输';
break;
case 'desktop':
currentMode = '桌面共享';
break;
}
switch (value) {
case 'file':
targetMode = '文件传输';
break;
case 'text':
targetMode = '文字传输';
break;
case 'desktop':
targetMode = '桌面共享';
break;
}
showNotification(`当前${currentMode}会话进行中,已在新标签页打开${targetMode}`, 'info');
// 如果已有活跃连接且要切换到不同的tab显示确认对话框
setPendingTabSwitch(value);
setShowConfirmDialog(true);
return;
}
// 如果没有活跃连接,正常切换
setActiveTab(value as 'file' | 'text' | 'desktop');
updateUrlParams(value);
}, [updateUrlParams, isConnected, pickupCode, isConnecting, activeTab, showNotification]);
}, [updateUrlParams, isConnected, pickupCode, isConnecting, activeTab]);
// 确认切换tab
const confirmTabSwitch = useCallback(() => {
if (pendingTabSwitch) {
const currentUrl = window.location.origin + window.location.pathname;
const newUrl = `${currentUrl}?type=${pendingTabSwitch}`;
// 在新标签页打开
window.open(newUrl, '_blank');
// 关闭对话框并清理状态
setShowConfirmDialog(false);
setPendingTabSwitch('');
}
}, [pendingTabSwitch]);
// 取消切换tab
const cancelTabSwitch = useCallback(() => {
setShowConfirmDialog(false);
setPendingTabSwitch('');
}, []);
// 初始化文件传输
const initFileTransfer = useCallback((fileInfo: any) => {
@@ -811,6 +805,55 @@ export default function HomePage() {
<div className="h-8 sm:h-16"></div>
</div>
</div>
{/* 确认对话框 */}
<Dialog open={showConfirmDialog} onOpenChange={setShowConfirmDialog}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription>
{(() => {
let currentMode = '';
let targetMode = '';
switch (activeTab) {
case 'file':
currentMode = '文件传输';
break;
case 'text':
currentMode = '文字传输';
break;
case 'desktop':
currentMode = '桌面共享';
break;
}
switch (pendingTabSwitch) {
case 'file':
targetMode = '文件传输';
break;
case 'text':
targetMode = '文字传输';
break;
case 'desktop':
targetMode = '桌面共享';
break;
}
return `当前${currentMode}会话进行中,是否要在新标签页中打开${targetMode}`;
})()}
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={cancelTabSwitch}>
</Button>
<Button onClick={confirmTabSwitch}>
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}

View File

@@ -1,13 +1,15 @@
import { NextRequest, NextResponse } from 'next/server';
const GO_BACKEND_URL = process.env.GO_BACKEND_URL || 'http://localhost:8080';
import { getBackendUrl } from '@/lib/config';
export async function POST(request: NextRequest) {
try {
const body = await request.json();
// 使用配置管理获取后端URL
const backendUrl = getBackendUrl('/api/create-room');
// 转发请求到Go后端
const response = await fetch(`${GO_BACKEND_URL}/api/create-room`, {
const response = await fetch(backendUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',

View File

@@ -1,4 +1,5 @@
import { NextRequest, NextResponse } from 'next/server';
import { getBackendUrl } from '@/lib/config';
export async function POST(req: NextRequest) {
try {
@@ -13,7 +14,7 @@ export async function POST(req: NextRequest) {
}
// 调用后端API创建文字传输房间
const response = await fetch('http://localhost:8080/api/create-text-room', {
const response = await fetch(getBackendUrl('/api/create-text-room'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',

View File

@@ -1,6 +1,5 @@
import { NextRequest, NextResponse } from 'next/server';
const GO_BACKEND_URL = process.env.GO_BACKEND_URL || 'http://localhost:8080';
import { getBackendUrl } from '@/lib/config';
export async function GET(request: NextRequest) {
try {
@@ -15,7 +14,7 @@ export async function GET(request: NextRequest) {
}
// 转发请求到Go后端
const response = await fetch(`${GO_BACKEND_URL}/api/room-info?code=${code}`, {
const response = await fetch(getBackendUrl(`/api/room-info?code=${code}`), {
method: 'GET',
headers: {
'Content-Type': 'application/json',

View File

@@ -6,25 +6,35 @@ import { Github } from 'lucide-react';
export default function Hero() {
return (
<div className="text-center mb-8 sm:mb-12 animate-fade-in-up">
<div className="flex items-center justify-center space-x-3 mb-4">
<h1 className="text-3xl sm:text-4xl md:text-5xl font-bold bg-gradient-to-r from-blue-600 via-purple-600 to-indigo-600 bg-clip-text text-transparent">
</h1>
<a
href="https://github.com/MatrixSeven/file-transfer-go"
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center space-x-1 px-3 py-1.5 bg-slate-100 hover:bg-slate-200 text-slate-700 text-sm rounded-full transition-colors duration-200 hover:scale-105 transform"
>
<Github className="w-4 h-4" />
<span className="hidden sm:inline"></span>
</a>
</div>
<p className="text-base sm:text-lg text-slate-600 max-w-2xl mx-auto leading-relaxed px-4">
<h1 className="text-3xl sm:text-4xl md:text-5xl font-bold bg-gradient-to-r from-blue-600 via-purple-600 to-indigo-600 bg-clip-text text-transparent mb-4">
</h1>
<p className="text-base sm:text-lg text-slate-600 max-w-2xl mx-auto leading-relaxed px-4 mb-4">
<br />
<span className="text-sm sm:text-base text-slate-500"> - </span>
</p>
{/* GitHub开源链接 */}
<div className="flex flex-col items-center space-y-2">
<a
href="https://github.com/MatrixSeven/file-transfer-go"
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center space-x-2 px-4 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 text-sm rounded-lg transition-all duration-200 hover:scale-105 transform border border-slate-200 hover:border-slate-300"
>
<Github className="w-4 h-4" />
<span></span>
</a>
<a
href="https://github.com/MatrixSeven/file-transfer-go"
target="_blank"
rel="noopener noreferrer"
className="text-xs text-slate-400 font-mono hover:text-slate-600 transition-colors duration-200 hover:underline"
>
https://github.com/MatrixSeven/file-transfer-go
</a>
</div>
</div>
);
}

View File

@@ -0,0 +1,122 @@
"use client"
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const Dialog = DialogPrimitive.Root
const DialogTrigger = DialogPrimitive.Trigger
const DialogPortal = DialogPrimitive.Portal
const DialogClose = DialogPrimitive.Close
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
/>
))
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
))
DialogContent.displayName = DialogPrimitive.Content.displayName
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className
)}
{...props}
/>
)
DialogHeader.displayName = "DialogHeader"
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
DialogFooter.displayName = "DialogFooter"
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
DialogTitle.displayName = DialogPrimitive.Title.displayName
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
DialogDescription.displayName = DialogPrimitive.Description.displayName
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogClose,
DialogTrigger,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
}

View File

@@ -0,0 +1,77 @@
/**
* 环境配置管理
*/
export const config = {
// 环境判断
isDev: process.env.NODE_ENV === 'development',
isProd: process.env.NODE_ENV === 'production',
// API配置
api: {
// 后端API地址 (服务器端使用)
backendUrl: process.env.GO_BACKEND_URL || 'http://localhost:8080',
// 前端API基础URL (客户端使用)
baseUrl: process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:3000',
// WebSocket地址
wsUrl: process.env.NEXT_PUBLIC_WS_URL || 'ws://localhost:8080/ws',
},
// 超时配置
timeout: {
api: 30000, // 30秒
ws: 60000, // 60秒
},
// 重试配置
retry: {
max: 3,
delay: 1000,
},
}
/**
* 获取后端API完整URL
* @param path API路径
* @returns 完整的API URL
*/
export function getBackendUrl(path: string): string {
const baseUrl = config.api.backendUrl.replace(/\/$/, '')
const apiPath = path.startsWith('/') ? path : `/${path}`
return `${baseUrl}${apiPath}`
}
/**
* 获取前端API完整URL
* @param path API路径
* @returns 完整的API URL
*/
export function getApiUrl(path: string): string {
const baseUrl = config.api.baseUrl.replace(/\/$/, '')
const apiPath = path.startsWith('/') ? path : `/${path}`
return `${baseUrl}${apiPath}`
}
/**
* 获取WebSocket URL
* @returns WebSocket连接地址
*/
export function getWsUrl(): string {
return config.api.wsUrl
}
/**
* 环境配置调试信息
*/
export function getEnvInfo() {
return {
environment: process.env.NODE_ENV,
backendUrl: config.api.backendUrl,
baseUrl: config.api.baseUrl,
wsUrl: config.api.wsUrl,
isDev: config.isDev,
isProd: config.isProd,
}
}