feat: 初始提交 - Code Server Bridge完整实现
- OAuth认证系统(Gitea + Lua扩展) - Git自动化操作(本地/SSH远程) - 实时进度WebSocket推送 - 现代化Tab界面UI - Cobra CLI命令行(init/version/serve) - 完整构建系统(Makefile + Taskfile) - UPX压缩支持(体积减少70%)
This commit is contained in:
85
internal/http/handlers/auth_cs.go
Normal file
85
internal/http/handlers/auth_cs.go
Normal file
@@ -0,0 +1,85 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"cs-bridge/internal/auth"
|
||||
"cs-bridge/pkg/logger"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// ValidateTokenResponse Token验证响应结构
|
||||
type ValidateTokenResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Workspace string `json:"workspace,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// ValidateWorkspaceToken Token验证处理器(供nginx调用)
|
||||
// nginx通过此接口验证token并获取workspace路径
|
||||
func ValidateWorkspaceToken() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
log := logger.GetLogger()
|
||||
|
||||
// 获取token参数 - 优先从query获取,否则从header获取(nginx auth_request场景)
|
||||
token := r.URL.Query().Get("token")
|
||||
if token == "" {
|
||||
token = r.Header.Get("X-Auth-Token")
|
||||
}
|
||||
|
||||
log.Info("[Auth] 收到验证请求",
|
||||
zap.String("url", r.URL.String()),
|
||||
zap.Bool("has_token", token != ""))
|
||||
|
||||
if token == "" {
|
||||
// 无token时返回200,允许请求通过(不设置X-Workspace)
|
||||
// 这样静态资源等请求可以正常访问
|
||||
log.Debug("[Auth] 无token, 允许通过")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
|
||||
// 验证token (可多次使用,直到过期)
|
||||
log.Info(fmt.Sprintf("[Auth] 开始验证token: %s...", token[:min(16, len(token))]))
|
||||
workspacePath, err := auth.ValidateAndConsumeToken(token)
|
||||
if err != nil {
|
||||
log.Error(fmt.Sprintf("[Auth] Token验证失败: %v", err))
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
// 根据错误类型返回不同的状态码
|
||||
switch err {
|
||||
case auth.ErrTokenNotFound:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
case auth.ErrTokenExpired:
|
||||
w.WriteHeader(http.StatusGone)
|
||||
default:
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
json.NewEncoder(w).Encode(ValidateTokenResponse{
|
||||
Success: false,
|
||||
Error: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
log.Info(fmt.Sprintf("[Auth] Token验证成功, Workspace: %s", workspacePath))
|
||||
|
||||
// 返回成功响应
|
||||
w.Header().Set("X-Workspace", workspacePath)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(ValidateTokenResponse{
|
||||
Success: true,
|
||||
Workspace: workspacePath,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
25
internal/http/handlers/entry.go
Normal file
25
internal/http/handlers/entry.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"cs-bridge/internal/config"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func Entry(cfg *config.CodeServer) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
workspaceID := uuid.NewString()
|
||||
workspacePath := path.Join(cfg.WorkspaceRoot, workspaceID)
|
||||
|
||||
redirectURL, _ := url.Parse(cfg.BaseURL)
|
||||
|
||||
q := redirectURL.Query()
|
||||
q.Set("folder", workspacePath)
|
||||
redirectURL.RawQuery = q.Encode()
|
||||
|
||||
http.Redirect(w, r, redirectURL.String(), http.StatusFound)
|
||||
}
|
||||
}
|
||||
84
internal/http/handlers/oauth.go
Normal file
84
internal/http/handlers/oauth.go
Normal file
@@ -0,0 +1,84 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"cs-bridge/internal/http/middleware"
|
||||
"cs-bridge/internal/oauth"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
func OauthLogin(mgr *oauth.Manager) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
name := chi.URLParam(r, "provider")
|
||||
p, err := mgr.Get(name)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 404)
|
||||
return
|
||||
}
|
||||
|
||||
state := oauth.NewState()
|
||||
session, err := middleware.GetSession(r)
|
||||
session.Values["oauth_state"] = state
|
||||
session.Values["oauth_provider"] = name
|
||||
session.Save(r, w)
|
||||
|
||||
redirectURL, _ := p.AuthURL(state)
|
||||
|
||||
http.Redirect(w, r, redirectURL, http.StatusFound)
|
||||
}
|
||||
}
|
||||
|
||||
func OauthCallBack(mgr *oauth.Manager) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
name := chi.URLParam(r, "provider")
|
||||
p, err := mgr.Get(name)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 404)
|
||||
return
|
||||
}
|
||||
|
||||
session, _ := middleware.GetSession(r)
|
||||
expectedState, ok := session.Values["oauth_state"].(string)
|
||||
if !ok {
|
||||
http.Error(w, "missing oauth state", 400)
|
||||
return
|
||||
}
|
||||
|
||||
goState := r.URL.Query().Get("state")
|
||||
if goState != expectedState {
|
||||
http.Error(w, "invaild oauth state2", 400)
|
||||
return
|
||||
}
|
||||
|
||||
delete(session.Values, "oauth_state")
|
||||
|
||||
code := r.URL.Query().Get("code")
|
||||
token, err := p.Exchange(code)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 404)
|
||||
return
|
||||
}
|
||||
|
||||
userInfo, err := p.UserInfo(token)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
|
||||
// 只保存用户ID,避免session过大
|
||||
session.Values["uid"] = userInfo.UserId
|
||||
session.Values["username"] = userInfo.Username
|
||||
|
||||
// 获取登录前保存的URL
|
||||
redirectURL := "/"
|
||||
if savedURL, ok := session.Values["redirect_after_login"].(string); ok && savedURL != "" {
|
||||
redirectURL = savedURL
|
||||
delete(session.Values, "redirect_after_login") // 使用后删除
|
||||
}
|
||||
|
||||
session.Save(r, w)
|
||||
|
||||
http.Redirect(w, r, redirectURL, http.StatusFound)
|
||||
}
|
||||
}
|
||||
630
internal/http/handlers/prepare.go
Normal file
630
internal/http/handlers/prepare.go
Normal file
@@ -0,0 +1,630 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"crypto/sha1"
|
||||
"cs-bridge/internal/config"
|
||||
gitpkg "cs-bridge/pkg/git"
|
||||
"cs-bridge/pkg/logger"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"path"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// GitProgressPage 显示git进度页面
|
||||
func GitProgressPage() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
// 获取repo参数
|
||||
repo := r.URL.Query().Get("repo")
|
||||
if repo == "" {
|
||||
http.Error(w, "Missing repo parameter", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// 返回HTML页面
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
logger.GetLogger().Info(fmt.Sprintf("[GitProgressPage] Repo参数: %s", repo))
|
||||
// 使用字符串替换避免fmt格式化问题
|
||||
html := strings.Replace(gitProgressHTML, "{{REPO_URL}}", repo, 1)
|
||||
w.Write([]byte(html))
|
||||
}
|
||||
}
|
||||
|
||||
// ExecuteGitRequest 执行git操作的请求结构
|
||||
type ExecuteGitRequest struct {
|
||||
RepoURL string `json:"repo_url"`
|
||||
}
|
||||
|
||||
// ExecuteGitResponse 执行git操作的响应结构
|
||||
type ExecuteGitResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Message string `json:"message"`
|
||||
RedirectURL string `json:"redirect_url,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// ExecuteGitOperations 执行git操作(克隆或更新)
|
||||
func ExecuteGitOperations(cfg *config.Config) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
// 解析请求
|
||||
var req ExecuteGitRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
SendProgressJSON(w, "error", "Invalid request", 0)
|
||||
return
|
||||
}
|
||||
|
||||
if req.RepoURL == "" {
|
||||
SendProgressJSON(w, "error", "Missing repo_url", 0)
|
||||
return
|
||||
}
|
||||
|
||||
log := logger.GetLogger()
|
||||
log.Info(fmt.Sprintf("[ExecuteGit] 开始执行Git操作, RepoURL: %s, ClientIP: %s", req.RepoURL, r.RemoteAddr))
|
||||
|
||||
// 生成workspace路径 - 使用客户端IP和仓库URL的SHA1哈希作为workspaceID
|
||||
repoName := gitpkg.GetRepoName(req.RepoURL)
|
||||
|
||||
// 基于客户端IP和仓库URL生成稳定的workspaceID
|
||||
// hashInput := r.RemoteAddr + ":" + req.RepoURL
|
||||
hashInput := req.RepoURL
|
||||
hasher := sha1.New()
|
||||
hasher.Write([]byte(hashInput))
|
||||
workspaceID := hex.EncodeToString(hasher.Sum(nil))[:16] // 取前16位
|
||||
|
||||
log.Info(fmt.Sprintf("[ExecuteGit] 生成workspaceID: %s (基于: %s)", workspaceID, hashInput))
|
||||
|
||||
// 容器内路径(传递给code-server) - 使用path.Join确保Linux风格路径
|
||||
containerWorkspacePath := path.Join(cfg.CodeServer.WorkspaceRoot, workspaceID, repoName)
|
||||
|
||||
// SSH服务器上的实际路径(用于git操作) - 使用path.Join确保Linux风格路径
|
||||
sshWorkspacePath := containerWorkspacePath
|
||||
if cfg.CodeServer.SSHWorkspaceRoot != "" {
|
||||
sshWorkspacePath = path.Join(cfg.CodeServer.SSHWorkspaceRoot, workspaceID, repoName)
|
||||
}
|
||||
|
||||
log.Info(fmt.Sprintf("[ExecuteGit] 路径配置 - Container: %s, SSH: %s", containerWorkspacePath, sshWorkspacePath))
|
||||
|
||||
// 进度回调函数
|
||||
progressCallback := func(message string, percent int) {
|
||||
SendProgressToClients("processing", message, percent)
|
||||
}
|
||||
|
||||
// 检查是否使用SSH远程执行
|
||||
useSSH := cfg.CodeServer.SSHHost != ""
|
||||
var sshCfg gitpkg.SSHConfig
|
||||
if useSSH {
|
||||
sshCfg = gitpkg.SSHConfig{
|
||||
Host: cfg.CodeServer.SSHHost,
|
||||
Port: cfg.CodeServer.SSHPort,
|
||||
User: cfg.CodeServer.SSHUser,
|
||||
KeyPath: cfg.CodeServer.SSHKeyPath,
|
||||
}
|
||||
}
|
||||
|
||||
// 检查仓库是否存在
|
||||
SendProgressToClients("checking", "正在检查仓库...", 5)
|
||||
|
||||
var err error
|
||||
var repoExists bool
|
||||
|
||||
if useSSH {
|
||||
repoExists = gitpkg.CheckRepoExistsRemote(sshCfg, sshWorkspacePath)
|
||||
} else {
|
||||
repoExists = gitpkg.CheckRepoExists(containerWorkspacePath)
|
||||
}
|
||||
|
||||
if repoExists {
|
||||
// 仓库存在,执行pull
|
||||
SendProgressToClients("pulling", "仓库已存在,正在更新...", 20)
|
||||
if useSSH {
|
||||
err = gitpkg.PullRepoRemote(sshCfg, sshWorkspacePath, progressCallback)
|
||||
} else {
|
||||
err = gitpkg.PullRepo(containerWorkspacePath, progressCallback)
|
||||
}
|
||||
} else {
|
||||
// 仓库不存在,执行clone
|
||||
SendProgressToClients("cloning", "仓库不存在,正在克隆...", 20)
|
||||
if useSSH {
|
||||
err = gitpkg.CloneRepoRemote(sshCfg, req.RepoURL, sshWorkspacePath, progressCallback)
|
||||
} else {
|
||||
err = gitpkg.CloneRepo(req.RepoURL, containerWorkspacePath, progressCallback)
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
SendProgressToClients("error", fmt.Sprintf("Git操作失败: %v", err), 0)
|
||||
json.NewEncoder(w).Encode(ExecuteGitResponse{
|
||||
Success: false,
|
||||
Error: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Git操作成功,发送100%进度
|
||||
SendProgressToClients("success", "操作完成,即将跳转...", 100)
|
||||
|
||||
// 直接重定向到code-server,带folder参数
|
||||
redirectURL := fmt.Sprintf("%s?folder=%s", cfg.CodeServer.BaseURL, containerWorkspacePath)
|
||||
|
||||
log.Info(fmt.Sprintf("[ExecuteGit] 准备重定向到: %s", redirectURL))
|
||||
|
||||
// 返回成功响应
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(ExecuteGitResponse{
|
||||
Success: true,
|
||||
Message: "Git操作完成",
|
||||
RedirectURL: redirectURL,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// gitProgressHTML 是git进度页面的HTML模板
|
||||
const gitProgressHTML = `<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>准备工作区 - Loading...</title>
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 700px;
|
||||
width: 90%;
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
backdrop-filter: blur(20px);
|
||||
border-radius: 25px;
|
||||
padding: 50px;
|
||||
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.4), 0 0 100px rgba(255, 255, 255, 0.1) inset;
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
animation: slideUp 0.6s ease-out;
|
||||
}
|
||||
|
||||
@keyframes slideUp {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(30px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
h1 {
|
||||
text-align: center;
|
||||
margin-bottom: 35px;
|
||||
font-size: 32px;
|
||||
font-weight: 700;
|
||||
text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
|
||||
letter-spacing: -0.5px;
|
||||
}
|
||||
|
||||
.progress-container {
|
||||
background: rgba(0, 0, 0, 0.25);
|
||||
border-radius: 50px;
|
||||
height: 24px;
|
||||
overflow: hidden;
|
||||
margin-bottom: 25px;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2) inset;
|
||||
}
|
||||
|
||||
.progress-bar {
|
||||
background: linear-gradient(90deg, #4CAF50 0%, #8BC34A 50%, #CDDC39 100%);
|
||||
height: 100%;
|
||||
width: 0%;
|
||||
transition: width 0.4s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
border-radius: 50px;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.progress-bar::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: -100%;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
|
||||
animation: shimmer 2s infinite;
|
||||
}
|
||||
|
||||
@keyframes shimmer {
|
||||
to {
|
||||
left: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.status {
|
||||
text-align: center;
|
||||
font-size: 18px;
|
||||
margin-bottom: 25px;
|
||||
min-height: 30px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.log-container {
|
||||
background: rgba(0, 0, 0, 0.35);
|
||||
border-radius: 15px;
|
||||
padding: 25px;
|
||||
max-height: 350px;
|
||||
overflow-y: auto;
|
||||
font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Courier New', monospace;
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.log-container::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
.log-container::-webkit-scrollbar-track {
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.log-container::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.3);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.log-container::-webkit-scrollbar-thumb:hover {
|
||||
background: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
|
||||
.log-entry {
|
||||
margin-bottom: 10px;
|
||||
opacity: 0;
|
||||
animation: fadeIn 0.4s ease-out forwards;
|
||||
padding-left: 8px;
|
||||
border-left: 2px solid transparent;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.log-entry:hover {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-left-color: rgba(255, 255, 255, 0.4);
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(-5px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.spinner {
|
||||
display: inline-block;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border: 3px solid rgba(255, 255, 255, 0.3);
|
||||
border-top-color: #fff;
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
vertical-align: middle;
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
.error {
|
||||
color: #ff5252;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.success {
|
||||
color: #4CAF50;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* Tab导航 */
|
||||
.tab-navigation {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-bottom: 30px;
|
||||
border-bottom: 2px solid rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
|
||||
.tab-button {
|
||||
flex: 1;
|
||||
padding: 15px 20px;
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
border-bottom: 3px solid transparent;
|
||||
position: relative;
|
||||
bottom: -2px;
|
||||
}
|
||||
|
||||
.tab-button:hover {
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
}
|
||||
|
||||
.tab-button.active {
|
||||
color: #fff;
|
||||
border-bottom-color: #4CAF50;
|
||||
}
|
||||
|
||||
.tab-content {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.tab-content.active {
|
||||
display: block;
|
||||
animation: fadeIn 0.4s ease-out;
|
||||
}
|
||||
|
||||
/* 完成区域 */
|
||||
.completion-section {
|
||||
display: none;
|
||||
margin-top: 30px;
|
||||
padding-top: 30px;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.2);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.countdown-text {
|
||||
font-size: 20px;
|
||||
margin-bottom: 20px;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.countdown-number {
|
||||
font-size: 64px;
|
||||
font-weight: 700;
|
||||
color: #4CAF50;
|
||||
margin: 20px 0;
|
||||
text-shadow: 0 2px 20px rgba(76, 175, 80, 0.4);
|
||||
}
|
||||
|
||||
.redirect-button {
|
||||
background: linear-gradient(135deg, #4CAF50 0%, #8BC34A 100%);
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 16px 48px;
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
border-radius: 50px;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 4px 20px rgba(76, 175, 80, 0.4);
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.redirect-button:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 30px rgba(76, 175, 80, 0.6);
|
||||
}
|
||||
|
||||
.redirect-button:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h1>🚀 准备工作区</h1>
|
||||
|
||||
<!-- Tab导航 -->
|
||||
<div class="tab-navigation">
|
||||
<button class="tab-button active" onclick="switchTab('progress')" id="tabProgress">
|
||||
📊 进行中
|
||||
</button>
|
||||
<button class="tab-button" onclick="switchTab('complete')" id="tabComplete">
|
||||
✅ 已完成
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 进行中Tab -->
|
||||
<div class="tab-content active" id="progressTab">
|
||||
<div class="progress-container">
|
||||
<div class="progress-bar" id="progressBar"></div>
|
||||
</div>
|
||||
<div class="status" id="status">
|
||||
<span class="spinner"></span>
|
||||
<span>正在连接...</span>
|
||||
</div>
|
||||
<div class="log-container" id="logContainer">
|
||||
<div class="log-entry">等待服务器响应...</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 已完成Tab -->
|
||||
<div class="tab-content" id="completeTab">
|
||||
<div class="completion-section" style="display: block; margin-top: 0; padding-top: 0; border-top: none;">
|
||||
<div style="font-size: 48px; margin-bottom: 20px;">✅</div>
|
||||
<div style="font-size: 24px; margin-bottom: 30px; font-weight: 600;">工作区准备完成!</div>
|
||||
<div class="countdown-text">即将跳转到 Code Server...</div>
|
||||
<div class="countdown-number" id="countdown">3</div>
|
||||
<button class="redirect-button" onclick="redirectNow()">
|
||||
立即跳转 →
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const repoURL = '{{REPO_URL}}';
|
||||
const progressBar = document.getElementById('progressBar');
|
||||
const status = document.getElementById('status');
|
||||
const logContainer = document.getElementById('logContainer');
|
||||
|
||||
let ws;
|
||||
let isCompleted = false;
|
||||
|
||||
function addLog(message, isError = false) {
|
||||
const entry = document.createElement('div');
|
||||
entry.className = 'log-entry' + (isError ? ' error' : '');
|
||||
entry.textContent = '> ' + message;
|
||||
logContainer.appendChild(entry);
|
||||
logContainer.scrollTop = logContainer.scrollHeight;
|
||||
}
|
||||
|
||||
function updateProgress(percent) {
|
||||
progressBar.style.width = percent + '%';
|
||||
}
|
||||
|
||||
function updateStatus(message, showSpinner = true) {
|
||||
if (showSpinner) {
|
||||
status.innerHTML = '<span class="spinner"></span><span>' + message + '</span>';
|
||||
} else {
|
||||
status.innerHTML = '<span>' + message + '</span>';
|
||||
}
|
||||
}
|
||||
|
||||
function connectWebSocket() {
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const wsURL = protocol + '//' + window.location.host + '/ws/git-progress';
|
||||
|
||||
ws = new WebSocket(wsURL);
|
||||
|
||||
ws.onopen = function() {
|
||||
addLog('WebSocket连接已建立');
|
||||
// 连接建立后,开始执行git操作
|
||||
executeGitOperation();
|
||||
};
|
||||
|
||||
ws.onmessage = function(event) {
|
||||
const data = JSON.parse(event.data);
|
||||
addLog(data.message);
|
||||
updateProgress(data.percent);
|
||||
|
||||
if (data.status === 'error') {
|
||||
updateStatus('❌ ' + data.message, false);
|
||||
status.className = 'status error';
|
||||
} else if (data.status === 'success') {
|
||||
updateStatus('✅ ' + data.message, false);
|
||||
status.className = 'status success';
|
||||
isCompleted = true;
|
||||
} else {
|
||||
updateStatus(data.message, true);
|
||||
}
|
||||
};
|
||||
|
||||
ws.onerror = function() {
|
||||
addLog('WebSocket连接错误', true);
|
||||
};
|
||||
|
||||
ws.onclose = function() {
|
||||
addLog('WebSocket连接已关闭');
|
||||
};
|
||||
}
|
||||
|
||||
function executeGitOperation() {
|
||||
updateStatus('正在执行Git操作...', true);
|
||||
addLog('开始Git操作: ' + repoURL);
|
||||
|
||||
fetch('/api/git/execute', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
repo_url: repoURL
|
||||
})
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
addLog('✓ 操作成功完成');
|
||||
// 显示跳转页面
|
||||
showRedirectPage(data.redirect_url);
|
||||
} else {
|
||||
addLog('✗ 操作失败: ' + data.error, true);
|
||||
updateStatus('操作失败', false);
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
addLog('✗ 请求失败: ' + err.message, true);
|
||||
updateStatus('请求失败', false);
|
||||
});
|
||||
}
|
||||
|
||||
// Tab切换函数
|
||||
function switchTab(tabName) {
|
||||
// 更新按钮状态
|
||||
document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
|
||||
document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
|
||||
|
||||
if (tabName === 'progress') {
|
||||
document.getElementById('tabProgress').classList.add('active');
|
||||
document.getElementById('progressTab').classList.add('active');
|
||||
} else {
|
||||
document.getElementById('tabComplete').classList.add('active');
|
||||
document.getElementById('completeTab').classList.add('active');
|
||||
}
|
||||
}
|
||||
|
||||
// 显示完成页面并启动倒计时
|
||||
let redirectUrl = '';
|
||||
let countdownTimer = null;
|
||||
|
||||
function showRedirectPage(url) {
|
||||
redirectUrl = url;
|
||||
|
||||
// 等待1秒让进度条停留在100%
|
||||
setTimeout(() => {
|
||||
// 切换到已完成tab
|
||||
switchTab('complete');
|
||||
|
||||
// 启动3秒倒计时
|
||||
let count = 3;
|
||||
const countdownElement = document.getElementById('countdown');
|
||||
|
||||
countdownTimer = setInterval(() => {
|
||||
count--;
|
||||
if (count > 0) {
|
||||
countdownElement.textContent = count;
|
||||
} else {
|
||||
clearInterval(countdownTimer);
|
||||
redirectNow();
|
||||
}
|
||||
}, 1000);
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
// 立即跳转
|
||||
function redirectNow() {
|
||||
if (countdownTimer) {
|
||||
clearInterval(countdownTimer);
|
||||
}
|
||||
window.location.href = redirectUrl;
|
||||
}
|
||||
|
||||
// 启动
|
||||
connectWebSocket();
|
||||
</script>
|
||||
</body>
|
||||
</html>`
|
||||
149
internal/http/handlers/ws.go
Normal file
149
internal/http/handlers/ws.go
Normal file
@@ -0,0 +1,149 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
CheckOrigin: func(r *http.Request) bool {
|
||||
// 允许所有来源(生产环境应该做更严格的检查)
|
||||
return true
|
||||
},
|
||||
}
|
||||
|
||||
// ProgressMessage WebSocket进度消息结构
|
||||
type ProgressMessage struct {
|
||||
Status string `json:"status"` // 状态: checking, cloning, pulling, success, error
|
||||
Message string `json:"message"` // 消息文本
|
||||
Percent int `json:"percent"` // 进度百分比 (0-100)
|
||||
}
|
||||
|
||||
// ProgressHub 进度广播中心
|
||||
type ProgressHub struct {
|
||||
clients map[string]*websocket.Conn
|
||||
clientsMux sync.RWMutex
|
||||
broadcast chan ProgressMessage
|
||||
}
|
||||
|
||||
var (
|
||||
hub *ProgressHub
|
||||
hubOnce sync.Once
|
||||
)
|
||||
|
||||
// GetProgressHub 获取进度广播中心单例
|
||||
func GetProgressHub() *ProgressHub {
|
||||
hubOnce.Do(func() {
|
||||
hub = &ProgressHub{
|
||||
clients: make(map[string]*websocket.Conn),
|
||||
broadcast: make(chan ProgressMessage, 10),
|
||||
}
|
||||
go hub.run()
|
||||
})
|
||||
return hub
|
||||
}
|
||||
|
||||
// run 运行广播循环
|
||||
func (h *ProgressHub) run() {
|
||||
for msg := range h.broadcast {
|
||||
h.clientsMux.RLock()
|
||||
for clientID, conn := range h.clients {
|
||||
err := conn.WriteJSON(msg)
|
||||
if err != nil {
|
||||
// 写入失败,移除客户端
|
||||
conn.Close()
|
||||
h.clientsMux.RUnlock()
|
||||
h.removeClient(clientID)
|
||||
h.clientsMux.RLock()
|
||||
}
|
||||
}
|
||||
h.clientsMux.RUnlock()
|
||||
}
|
||||
}
|
||||
|
||||
// addClient 添加客户端
|
||||
func (h *ProgressHub) addClient(clientID string, conn *websocket.Conn) {
|
||||
h.clientsMux.Lock()
|
||||
defer h.clientsMux.Unlock()
|
||||
h.clients[clientID] = conn
|
||||
}
|
||||
|
||||
// removeClient 移除客户端
|
||||
func (h *ProgressHub) removeClient(clientID string) {
|
||||
h.clientsMux.Lock()
|
||||
defer h.clientsMux.Unlock()
|
||||
delete(h.clients, clientID)
|
||||
}
|
||||
|
||||
// SendProgress 发送进度消息
|
||||
func (h *ProgressHub) SendProgress(msg ProgressMessage) {
|
||||
select {
|
||||
case h.broadcast <- msg:
|
||||
case <-time.After(1 * time.Second):
|
||||
// 超时,丢弃消息
|
||||
}
|
||||
}
|
||||
|
||||
// GitProgressWS WebSocket处理器
|
||||
func GitProgressWS() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
// 升级HTTP连接到WebSocket
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to upgrade to WebSocket", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
// 生成客户端ID
|
||||
clientID := r.RemoteAddr + "-" + time.Now().Format("20060102150405")
|
||||
|
||||
// 添加到hub
|
||||
hub := GetProgressHub()
|
||||
hub.addClient(clientID, conn)
|
||||
defer hub.removeClient(clientID)
|
||||
|
||||
// 发送欢迎消息
|
||||
welcomeMsg := ProgressMessage{
|
||||
Status: "connected",
|
||||
Message: "WebSocket连接已建立",
|
||||
Percent: 0,
|
||||
}
|
||||
if err := conn.WriteJSON(welcomeMsg); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 保持连接,读取客户端消息(主要用于心跳)
|
||||
for {
|
||||
_, _, err := conn.ReadMessage()
|
||||
if err != nil {
|
||||
// 连接断开
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SendProgressToClients 辅助函数:向所有客户端发送进度
|
||||
func SendProgressToClients(status, message string, percent int) {
|
||||
hub := GetProgressHub()
|
||||
hub.SendProgress(ProgressMessage{
|
||||
Status: status,
|
||||
Message: message,
|
||||
Percent: percent,
|
||||
})
|
||||
}
|
||||
|
||||
// SendProgressJSON 辅助函数:发送JSON格式的进度消息
|
||||
func SendProgressJSON(w http.ResponseWriter, status, message string, percent int) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(ProgressMessage{
|
||||
Status: status,
|
||||
Message: message,
|
||||
Percent: percent,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user