| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337 |
- package httpfile
- import (
- "encoding/json"
- "fmt"
- "log"
- "net/http"
- "os"
- "path/filepath"
- "strings"
- "ftp-server/config"
- )
- // Server represents the HTTP file server
- type Server struct {
- config *config.Config
- }
- // NewServer creates a new HTTP file server
- func NewServer(cfg *config.Config) *Server {
- return &Server{config: cfg}
- }
- // Start starts the HTTP file server
- func (s *Server) Start() error {
- if !s.config.HTTPFile.Enable {
- return nil
- }
- rootDir := s.config.HTTPFile.RootDir
- if err := os.MkdirAll(rootDir, 0755); err != nil {
- return fmt.Errorf("failed to create root directory: %v", err)
- }
- mux := http.NewServeMux()
- // Serve HTML page
- mux.HandleFunc("/", s.handleFileBrowser)
- // API endpoints
- mux.HandleFunc("/api/list", s.apiListDir)
- mux.HandleFunc("/api/download", s.apiDownload)
- addr := fmt.Sprintf("%s:%d", s.config.HTTPFile.Host, s.config.HTTPFile.Port)
- log.Printf("HTTP file server listening on http://%s", addr)
- return http.ListenAndServe(addr, mux)
- }
- func (s *Server) handleFileBrowser(w http.ResponseWriter, r *http.Request) {
- if r.URL.Path != "/" {
- http.NotFound(w, r)
- return
- }
- w.Header().Set("Content-Type", "text/html; charset=utf-8")
- w.Write([]byte(fileBrowserHTML))
- }
- func (s *Server) apiListDir(w http.ResponseWriter, r *http.Request) {
- dir := r.URL.Query().Get("path")
- if dir == "" {
- dir = "/"
- }
- realPath := s.toRealPath(dir)
- entries, err := os.ReadDir(realPath)
- if err != nil {
- http.Error(w, `{"error":"Cannot read directory"}`, http.StatusInternalServerError)
- return
- }
- var files []map[string]interface{}
- for _, entry := range entries {
- info, _ := entry.Info()
- modTime := info.ModTime().Format("2006-01-02 15:04:05")
- size := info.Size()
- file := map[string]interface{}{
- "name": entry.Name(),
- "modTime": modTime,
- "size": formatSize(size),
- "isDir": entry.IsDir(),
- }
- if !entry.IsDir() {
- file["ext"] = strings.ToLower(filepath.Ext(entry.Name()))
- }
- files = append(files, file)
- }
- w.Header().Set("Content-Type", "application/json")
- json.NewEncoder(w).Encode(map[string]interface{}{
- "files": files,
- })
- }
- func (s *Server) apiDownload(w http.ResponseWriter, r *http.Request) {
- file := r.URL.Query().Get("file")
- if file == "" {
- http.Error(w, "Missing file parameter", http.StatusBadRequest)
- return
- }
- realPath := s.toRealPath(file)
- if info, err := os.Stat(realPath); err != nil || info.IsDir() {
- http.Error(w, "File not found", http.StatusNotFound)
- return
- }
- http.ServeFile(w, r, realPath)
- log.Printf("HTTP download: %s from %s", file, r.RemoteAddr)
- }
- func (s *Server) toRealPath(httpPath string) string {
- rootDir := s.config.HTTPFile.RootDir
- cleanPath := strings.TrimPrefix(httpPath, "/")
- return filepath.Join(rootDir, cleanPath)
- }
- func formatSize(size int64) string {
- switch {
- case size < 1024:
- return fmt.Sprintf("%d B", size)
- case size < 1024*1024:
- return fmt.Sprintf("%.1f KB", float64(size)/1024)
- case size < 1024*1024*1024:
- return fmt.Sprintf("%.1f MB", float64(size)/(1024*1024))
- default:
- return fmt.Sprintf("%.1f GB", float64(size)/(1024*1024*1024))
- }
- }
- // fileBrowserHTML is the embedded HTML page
- const fileBrowserHTML = `<!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>HTTP 文件服务器</title>
- <style>
- * { margin: 0; padding: 0; box-sizing: border-box; }
- body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; }
- .container { max-width: 1200px; margin: 0 auto; padding: 20px; }
- .header { background: white; border-radius: 12px; padding: 24px; margin-bottom: 20px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); }
- .header h1 { font-size: 28px; color: #333; margin-bottom: 8px; }
- .header p { color: #888; font-size: 14px; }
- .breadcrumb { background: white; border-radius: 12px; padding: 16px 24px; margin-bottom: 20px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
- .breadcrumb a { color: #667eea; text-decoration: none; font-weight: 500; padding: 4px 8px; border-radius: 6px; transition: background 0.2s; }
- .breadcrumb a:hover { background: #f0f4ff; }
- .breadcrumb span { color: #999; font-size: 20px; }
- .actions { background: white; border-radius: 12px; padding: 16px 24px; margin-bottom: 20px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
- .btn { padding: 10px 20px; border: none; border-radius: 8px; cursor: pointer; font-size: 14px; font-weight: 600; transition: all 0.3s; display: inline-flex; align-items: center; gap: 6px; }
- .btn-primary { background: linear-gradient(135deg, #667eea, #764ba2); color: white; }
- .btn-primary:hover { transform: translateY(-2px); box-shadow: 0 4px 15px rgba(102,126,234,0.4); }
- .btn-success { background: #28a745; color: white; }
- .btn-success:hover { background: #218838; }
- .btn-danger { background: #dc3545; color: white; }
- .btn-danger:hover { background: #c82333; }
- .btn-sm { padding: 6px 12px; font-size: 12px; }
- .file-list { background: white; border-radius: 12px; padding: 24px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); }
- table { width: 100%; border-collapse: collapse; }
- th, td { padding: 12px 16px; text-align: left; border-bottom: 1px solid #f0f0f0; font-size: 14px; }
- th { background: #fafafa; font-weight: 600; color: #555; }
- tr:hover { background: #f8f9ff; }
- .file-name { display: flex; align-items: center; gap: 8px; }
- .file-icon { width: 32px; height: 32px; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 18px; }
- .folder-icon { background: #ffeaa7; }
- .file-icon-doc { background: #74b9ff; }
- .file-icon-img { background: #ff7675; }
- .file-icon-zip { background: #a29bfe; }
- .file-icon-code { background: #55efc4; }
- .file-icon-other { background: #dfe6e9; }
- .file-link { color: #667eea; text-decoration: none; font-weight: 500; }
- .file-link:hover { text-decoration: underline; }
- .actions-cell { display: flex; gap: 8px; }
- .toast { position: fixed; top: 80px; right: 30px; padding: 14px 24px; border-radius: 8px; color: white; font-size: 14px; font-weight: 500; z-index: 2000; animation: slideIn 0.3s ease; }
- .toast-success { background: #28a745; }
- .toast-error { background: #dc3545; }
- @keyframes slideIn { from { transform: translateX(100px); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
- .modal-overlay { display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 1000; justify-content: center; align-items: center; }
- .modal-overlay.show { display: flex; }
- .modal { background: white; border-radius: 12px; padding: 30px; width: 480px; max-width: 90%; }
- .modal h2 { margin-bottom: 24px; font-size: 20px; }
- .modal-actions { display: flex; justify-content: flex-end; gap: 12px; margin-top: 24px; }
- .form-group { margin-bottom: 16px; }
- .form-group label { display: block; margin-bottom: 6px; font-weight: 600; color: #555; font-size: 14px; }
- .form-group input { width: 100%; padding: 10px 14px; border: 1px solid #ddd; border-radius: 6px; font-size: 14px; }
- .form-group input:focus { outline: none; border-color: #667eea; }
- .drop-zone { border: 2px dashed #667eea; border-radius: 8px; padding: 40px 20px; text-align: center; background: #f8f9ff; transition: all 0.3s; cursor: pointer; margin-bottom: 16px; }
- .drop-zone:hover, .drop-zone.dragover { background: #e8ebff; border-color: #764ba2; }
- .progress-bar { width: 100%; height: 8px; background: #f0f0f0; border-radius: 4px; overflow: hidden; margin-top: 12px; display: none; }
- .progress-bar.show { display: block; }
- .progress-fill { height: 100%; background: linear-gradient(135deg, #667eea, #764ba2); transition: width 0.3s; width: 0%; }
- .empty-state { text-align: center; padding: 60px 20px; color: #999; }
- .empty-state .icon { font-size: 64px; margin-bottom: 16px; }
- </style>
- </head>
- <body>
- <div class="container">
- <div class="header">
- <h1>📁 HTTP 文件服务器</h1>
- <p>在线浏览、下载文件</p>
- </div>
- <div class="breadcrumb" id="breadcrumb">
- </div>
- <div class="actions">
- <button class="btn btn-primary" onclick="refresh()">
- 🔄 刷新
- </button>
- </div>
- <div class="file-list">
- <table id="fileTable">
- <thead>
- <tr><th>名称</th><th>大小</th><th>修改时间</th><th>操作</th></tr>
- </thead>
- <tbody id="fileTableBody">
- </tbody>
- </table>
- <div class="empty-state" id="emptyState" style="display:none">
- <div class="icon">📁</div>
- <div>目录为空</div>
- </div>
- </div>
- </div>
- <script>
- let currentPath = '/';
- function init() {
- loadFiles();
- }
- function loadFiles() {
- fetch('/api/list?path=' + encodeURIComponent(currentPath))
- .then(r => r.json())
- .then(data => {
- const tbody = document.getElementById('fileTableBody');
- tbody.innerHTML = '';
- if (!data.files || data.files.length === 0) {
- document.getElementById('emptyState').style.display = 'block';
- document.getElementById('fileTable').style.display = 'none';
- return;
- }
- document.getElementById('emptyState').style.display = 'none';
- document.getElementById('fileTable').style.display = 'table';
- data.files.forEach(f => {
- const tr = document.createElement('tr');
- const icon = f.isDir ? '📁' : getFileIcon(f.name);
- const iconClass = f.isDir ? 'folder-icon' : 'file-icon-' + getFileType(f.name);
- tr.innerHTML = '<td><div class="file-name"><div class="file-icon ' + iconClass + '">' + icon + '</div>' +
- (f.isDir ? '<a class="file-link" href="#" onclick="enterFolder(\\'' + escapeStr(f.name) + '\\');return false;">' + f.name + '</a>' : '<span>' + f.name + '</span>') +
- '</div></td><td>' + (f.isDir ? '-' : f.size) + '</td><td>' + f.modTime + '</td><td class="actions-cell">' +
- (f.isDir ? '<button class="btn btn-sm btn-primary" onclick="enterFolder(\\'' + escapeStr(f.name) + '\\')">打开</button>' : '<a href="/api/download?file=' + encodeURIComponent(currentPath + f.name) + '" class="btn btn-sm btn-success">下载</a>') +
- '</td></tr>';
- tbody.appendChild(tr);
- });
- updateBreadcrumb();
- });
- }
- function escapeStr(s) {
- return s.replace(/\\/g, '\\\\\\\\').replace(/'/g, "\\\\'");
- }
- function enterFolder(name) {
- currentPath = currentPath === '/' ? '/' + name + '/' : currentPath + name + '/';
- loadFiles();
- }
- function updateBreadcrumb() {
- const bc = document.getElementById('breadcrumb');
- bc.innerHTML = '<a href="#" onclick="goTo(\'/\');return false;">根目录</a>';
-
- const parts = currentPath.split('/').filter(p => p);
- let path = '';
- parts.forEach(p => {
- path += p + '/';
- bc.innerHTML += '<span>/</span><a href="#" onclick="goTo(\\'' + path + '\\');return false;">' + p + '</a>';
- });
- }
- function goTo(path) {
- currentPath = path;
- loadFiles();
- }
- function refresh() {
- loadFiles();
- }
- function getFileIcon(name) {
- const ext = name.split('.').pop().toLowerCase();
- const icons = {
- 'doc': '📄', 'docx': '📄', 'pdf': '📄', 'txt': '📄',
- 'xls': '📊', 'xlsx': '📊', 'csv': '📊',
- 'jpg': '🖼️', 'jpeg': '🖼️', 'png': '🖼️', 'gif': '🖼️', 'bmp': '🖼️',
- 'mp3': '🎵', 'wav': '🎵', 'flac': '🎵',
- 'mp4': '🎬', 'avi': '🎬', 'mkv': '🎬', 'mov': '🎬',
- 'zip': '📦', 'rar': '📦', '7z': '📦', 'tar': '📦', 'gz': '📦',
- 'js': '💻', 'ts': '💻', 'py': '💻', 'go': '💻', 'java': '💻', 'c': '💻', 'cpp': '💻', 'html': '💻', 'css': '💻', 'json': '💻', 'xml': '💻', 'yml': '💻', 'yaml': '💻',
- };
- return icons[ext] || '📄';
- }
- function getFileType(name) {
- const ext = name.split('.').pop().toLowerCase();
- if (['jpg','jpeg','png','gif','bmp','svg'].includes(ext)) return 'img';
- if (['zip','rar','7z','tar','gz'].includes(ext)) return 'zip';
- if (['js','ts','py','go','java','c','cpp','html','css','json','xml','yml','yaml'].includes(ext)) return 'code';
- return 'doc';
- }
- function showToast(msg, type) {
- const toast = document.createElement('div');
- toast.className = 'toast ' + (type === 'error' ? 'toast-error' : 'toast-success');
- toast.textContent = msg;
- document.body.appendChild(toast);
- setTimeout(() => toast.remove(), 3000);
- }
- init();
- </script>
- </body>
- </html>
- `
|