Files
QuickStack/backend/golang.py
2026-02-14 00:46:04 +08:00

203 lines
5.4 KiB
Python

# -*- coding: utf-8 -*-
"""
Go 后端项目初始化模块
"""
import subprocess
import sys
def run_command_with_progress(cmd, cwd, description):
"""运行命令并显示实时输出"""
try:
print(f"\n{'=' * 60}")
print(f"执行: {description}")
print(f"{'=' * 60}")
process = subprocess.Popen(
cmd,
cwd=cwd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=0
)
for line in process.stdout:
try:
decoded_line = line.decode('utf-8', errors='replace')
except:
try:
decoded_line = line.decode('gbk', errors='replace')
except:
decoded_line = line.decode('latin-1', errors='replace')
print(decoded_line, end='')
process.wait()
if process.returncode == 0:
print(f"\n{'=' * 60}")
print(f"{description} - 完成")
print(f"{'=' * 60}\n")
return True
else:
print(f"\n{'=' * 60}")
print(f"{description} - 失败 (错误码: {process.returncode})")
print(f"{'=' * 60}\n")
return False
except Exception as e:
print(f"\n❌ 执行失败: {str(e)}")
return False
def init_golang_project(backend_dir, project_name):
"""初始化 Go 后端项目"""
print("\n🚀 初始化 Go 后端项目...")
# 初始化 Go 模块
success = run_command_with_progress(
f"go mod init {project_name}-backend",
backend_dir,
"初始化 Go 模块"
)
if not success:
print("\n💡 提示: 请确保已安装 Go")
print(" 下载地址: https://golang.org/dl/")
sys.exit(1)
# 创建 main.go - 使用标准库
main_go = backend_dir / "main.go"
main_go.write_text(f'''package main
import (
"encoding/json"
"log"
"net/http"
)
func main() {{
mux := http.NewServeMux()
// 健康检查接口
mux.HandleFunc("GET /api/health", healthHandler)
// 添加 CORS 中间件
handler := corsMiddleware(mux)
log.Println("🚀 服务器启动: http://localhost:8080")
log.Println("📍 健康检查: http://localhost:8080/api/health")
log.Fatal(http.ListenAndServe(":8080", handler))
}}
func healthHandler(w http.ResponseWriter, r *http.Request) {{
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{{
"status": "ok",
"message": "Welcome to {project_name} API",
}})
}}
func corsMiddleware(next http.Handler) http.Handler {{
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {{
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
if r.Method == "OPTIONS" {{
w.WriteHeader(http.StatusNoContent)
return
}}
next.ServeHTTP(w, r)
}})
}}
''', encoding='utf-8')
# 整理依赖
run_command_with_progress("go mod tidy", backend_dir, "整理 Go 依赖")
print("\n✅ Go 后端项目初始化成功")
print("💡 启动命令: go run main.go")
print("📝 注意: 使用 Go 标准库,无需第三方依赖")
def init_gin_project(backend_dir, project_name):
"""初始化 Go Gin 后端项目"""
print("\n🚀 初始化 Go Gin 后端项目...")
# 初始化 Go 模块
success = run_command_with_progress(
f"go mod init {project_name}-backend",
backend_dir,
"初始化 Go 模块"
)
if not success:
print("\n💡 提示: 请确保已安装 Go")
print(" 下载地址: https://golang.org/dl/")
sys.exit(1)
# 拉取 Gin 依赖
deps_ok = run_command_with_progress(
"go get github.com/gin-gonic/gin github.com/gin-contrib/cors",
backend_dir,
"安装 Gin 依赖"
)
if not deps_ok:
print("\n❌ 无法安装 Gin 依赖,请检查 Go 环境和网络")
sys.exit(1)
# 创建 main.go - Gin 框架
main_go = backend_dir / "main.go"
main_go.write_text(f'''package main
import (
"log"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func main() {{
r := gin.New()
r.Use(gin.Logger())
r.Use(gin.Recovery())
// CORS 配置
r.Use(cors.New(cors.Config{{
AllowOrigins: []string{{"*"}},
AllowMethods: []string{{"GET", "POST", "PUT", "DELETE", "OPTIONS"}},
AllowHeaders: []string{{"Origin", "Content-Type", "Authorization"}},
ExposeHeaders: []string{{"Content-Length"}},
AllowCredentials: false,
MaxAge: 12 * time.Hour,
}}))
// 健康检查
r.GET("/api/health", func(c *gin.Context) {{
c.JSON(200, gin.H{{
"status": "ok",
"message": "Welcome to {project_name} API",
}})
}})
addr := ":8080"
log.Printf("🚀 Gin 服务启动: http://localhost%s", addr)
log.Printf("📍 健康检查: http://localhost%s/api/health", addr)
if err := r.Run(addr); err != nil {{
log.Fatalf("启动失败: %v", err)
}}
}}
''', encoding='utf-8')
# 整理依赖
run_command_with_progress("go mod tidy", backend_dir, "整理 Go 依赖")
print("\n✅ Go Gin 后端项目初始化成功")
print("💡 启动命令: go run main.go")