| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347 |
- 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.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
- w.Header().Set("Pragma", "no-cache")
- w.Header().Set("Expires", "0")
- 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-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; }
- .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>
- var currentPath = '/';
- function init() {
- loadFiles();
- }
- function loadFiles() {
- fetch('/api/list?path=' + encodeURIComponent(currentPath))
- .then(function(r) { return r.json(); })
- .then(function(data) {
- var 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(function(f) {
- var tr = document.createElement('tr');
-
- var nameTd = document.createElement('td');
- var nameDiv = document.createElement('div');
- nameDiv.className = 'file-name';
- var iconDiv = document.createElement('div');
- var icon = f.isDir ? '📁' : getFileIcon(f.name);
- var iconClass = f.isDir ? 'folder-icon' : 'file-icon-' + getFileType(f.name);
- iconDiv.className = 'file-icon ' + iconClass;
- iconDiv.innerHTML = icon;
- nameDiv.appendChild(iconDiv);
-
- if (f.isDir) {
- var link = document.createElement('a');
- link.className = 'file-link';
- link.href = '#';
- link.textContent = f.name;
- link.onclick = function() { enterFolder(f.name); return false; };
- nameDiv.appendChild(link);
- } else {
- var span = document.createElement('span');
- span.textContent = f.name;
- nameDiv.appendChild(span);
- }
- nameTd.appendChild(nameDiv);
-
- var sizeTd = document.createElement('td');
- sizeTd.textContent = f.isDir ? '-' : f.size;
-
- var timeTd = document.createElement('td');
- timeTd.textContent = f.modTime;
-
- var actionTd = document.createElement('td');
- actionTd.className = 'actions-cell';
- if (f.isDir) {
- var btn = document.createElement('button');
- btn.className = 'btn btn-sm btn-primary';
- btn.textContent = '打开';
- btn.onclick = function() { enterFolder(f.name); };
- actionTd.appendChild(btn);
- } else {
- var link = document.createElement('a');
- link.className = 'btn btn-sm btn-success';
- link.href = '/api/download?file=' + encodeURIComponent(currentPath + f.name);
- link.textContent = '下载';
- actionTd.appendChild(link);
- }
-
- tr.appendChild(nameTd);
- tr.appendChild(sizeTd);
- tr.appendChild(timeTd);
- tr.appendChild(actionTd);
- tbody.appendChild(tr);
- });
- updateBreadcrumb();
- });
- }
- function enterFolder(name) {
- currentPath = currentPath === '/' ? '/' + name + '/' : currentPath + name + '/';
- loadFiles();
- }
- function updateBreadcrumb() {
- var bc = document.getElementById('breadcrumb');
- bc.innerHTML = '<a href="#" onclick="goTo(\'/\');return false;">根目录</a>';
-
- var parts = currentPath.split('/').filter(function(p) { return p; });
- var path = '';
- parts.forEach(function(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) {
- var ext = name.split('.').pop().toLowerCase();
- var 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) {
- var ext = name.split('.').pop().toLowerCase();
- if (['jpg','jpeg','png','gif','bmp','svg'].indexOf(ext) !== -1) return 'img';
- if (['zip','rar','7z','tar','gz'].indexOf(ext) !== -1) return 'zip';
- if (['js','ts','py','go','java','c','cpp','html','css','json','xml','yml','yaml'].indexOf(ext) !== -1) return 'code';
- return 'doc';
- }
- init();
- </script>
- </body>
- </html>
- `
|