#!/bin/bash # Hot-Reload Dev Script for TopFans Backend # Usage: ./dev.sh # # Requires: fswatch (Mac: brew install fswatch) or inotifywait (Linux) set -e RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' CYAN='\033[0;36m' NC='\033[0m' SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" cd "$SCRIPT_DIR" # Detect platform if [[ "$(uname)" == "Darwin" ]]; then WATCHER_TOOL="fswatch" WATCHER_CMD="fswatch -r" elif [[ "$(uname)" == "Linux" ]]; then WATCHER_TOOL="inotifywait" WATCHER_CMD="inotifywait -r -m -e modify,create,write" else echo -e "${RED}不支持的平台${NC}" exit 1 fi if ! command -v "$WATCHER_TOOL" &> /dev/null; then echo -e "${RED}缺少工具: $WATCHER_TOOL${NC}" if [[ "$(uname)" == "Darwin" ]]; then echo "安装方法: brew install fswatch" else echo "安装方法: sudo apt install inotify-tools (Debian/Ubuntu)" echo " sudo yum install inotify-tools (CentOS/RHEL)" fi exit 1 fi ENV_FILE="$SCRIPT_DIR/.env" if [ -f "$ENV_FILE" ]; then echo -e "${GREEN}📄 加载 .env 文件...${NC}" set -a source "$ENV_FILE" set +a fi DB_HOST="${DB_HOST:-localhost}" DB_PORT="${DB_PORT:-5432}" DB_USER="${DB_USER:-haihuizhu}" DB_PASSWORD="${DB_PASSWORD:-admin}" DB_NAME="${DB_NAME:-top-fans}" DB_ARGS=(-db-host="$DB_HOST" -db-port="$DB_PORT" -db-user="$DB_USER" -db-password="$DB_PASSWORD" -db-name="$DB_NAME") # 启动一个服务 # 用法: start_service name binary port use_db start_service() { local name=$1 local binary=$2 local port=$3 local use_db=$4 echo -e "${GREEN}🚀 启动 $name...${NC}" if [ "$use_db" = "1" ]; then "$SCRIPT_DIR/$binary" -port=$port "${DB_ARGS[@]}" > "/tmp/${name}.log" 2>&1 & else "$SCRIPT_DIR/$binary" -port=$port > "/tmp/${name}.log" 2>&1 & fi local pid=$! sleep 2 if ps -p $pid > /dev/null 2>&1; then echo -e "${GREEN}✅ $name 已启动 (PID: $pid, 端口: $port)${NC}" else echo -e "${RED}❌ $name 启动失败${NC}" echo -e "${YELLOW}查看日志: tail -f /tmp/${name}.log${NC}" fi } # 构建一个服务(在服务目录下执行 go build) # 用法: build_service name dir binary build_service() { local name=$1 local dir=$2 local binary=$3 if [ ! -d "$SCRIPT_DIR/$dir" ]; then echo -e "${RED}❌ $dir 目录不存在${NC}" return 1 fi cd "$SCRIPT_DIR/$dir" if go build -o "$SCRIPT_DIR/$binary" . 2>&1; then echo -e "${GREEN}✅ $name 编译成功${NC}" return 0 else echo -e "${RED}❌ $name 编译失败${NC}" return 1 fi }