server.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. package httpfile
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. "ftp-server/config"
  11. )
  12. // Server represents the HTTP file server
  13. type Server struct {
  14. config *config.Config
  15. }
  16. // NewServer creates a new HTTP file server
  17. func NewServer(cfg *config.Config) *Server {
  18. return &Server{config: cfg}
  19. }
  20. // Start starts the HTTP file server
  21. func (s *Server) Start() error {
  22. if !s.config.HTTPFile.Enable {
  23. return nil
  24. }
  25. rootDir := s.config.HTTPFile.RootDir
  26. if err := os.MkdirAll(rootDir, 0755); err != nil {
  27. return fmt.Errorf("failed to create root directory: %v", err)
  28. }
  29. mux := http.NewServeMux()
  30. // Serve HTML page
  31. mux.HandleFunc("/", s.handleFileBrowser)
  32. // API endpoints
  33. mux.HandleFunc("/api/list", s.apiListDir)
  34. mux.HandleFunc("/api/download", s.apiDownload)
  35. addr := fmt.Sprintf("%s:%d", s.config.HTTPFile.Host, s.config.HTTPFile.Port)
  36. log.Printf("HTTP file server listening on http://%s", addr)
  37. return http.ListenAndServe(addr, mux)
  38. }
  39. func (s *Server) handleFileBrowser(w http.ResponseWriter, r *http.Request) {
  40. if r.URL.Path != "/" {
  41. http.NotFound(w, r)
  42. return
  43. }
  44. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  45. w.Write([]byte(fileBrowserHTML))
  46. }
  47. func (s *Server) apiListDir(w http.ResponseWriter, r *http.Request) {
  48. dir := r.URL.Query().Get("path")
  49. if dir == "" {
  50. dir = "/"
  51. }
  52. realPath := s.toRealPath(dir)
  53. entries, err := os.ReadDir(realPath)
  54. if err != nil {
  55. http.Error(w, `{"error":"Cannot read directory"}`, http.StatusInternalServerError)
  56. return
  57. }
  58. var files []map[string]interface{}
  59. for _, entry := range entries {
  60. info, _ := entry.Info()
  61. modTime := info.ModTime().Format("2006-01-02 15:04:05")
  62. size := info.Size()
  63. file := map[string]interface{}{
  64. "name": entry.Name(),
  65. "modTime": modTime,
  66. "size": formatSize(size),
  67. "isDir": entry.IsDir(),
  68. }
  69. if !entry.IsDir() {
  70. file["ext"] = strings.ToLower(filepath.Ext(entry.Name()))
  71. }
  72. files = append(files, file)
  73. }
  74. w.Header().Set("Content-Type", "application/json")
  75. json.NewEncoder(w).Encode(map[string]interface{}{
  76. "files": files,
  77. })
  78. }
  79. func (s *Server) apiDownload(w http.ResponseWriter, r *http.Request) {
  80. file := r.URL.Query().Get("file")
  81. if file == "" {
  82. http.Error(w, "Missing file parameter", http.StatusBadRequest)
  83. return
  84. }
  85. realPath := s.toRealPath(file)
  86. if info, err := os.Stat(realPath); err != nil || info.IsDir() {
  87. http.Error(w, "File not found", http.StatusNotFound)
  88. return
  89. }
  90. http.ServeFile(w, r, realPath)
  91. log.Printf("HTTP download: %s from %s", file, r.RemoteAddr)
  92. }
  93. func (s *Server) toRealPath(httpPath string) string {
  94. rootDir := s.config.HTTPFile.RootDir
  95. cleanPath := strings.TrimPrefix(httpPath, "/")
  96. return filepath.Join(rootDir, cleanPath)
  97. }
  98. func formatSize(size int64) string {
  99. switch {
  100. case size < 1024:
  101. return fmt.Sprintf("%d B", size)
  102. case size < 1024*1024:
  103. return fmt.Sprintf("%.1f KB", float64(size)/1024)
  104. case size < 1024*1024*1024:
  105. return fmt.Sprintf("%.1f MB", float64(size)/(1024*1024))
  106. default:
  107. return fmt.Sprintf("%.1f GB", float64(size)/(1024*1024*1024))
  108. }
  109. }
  110. // fileBrowserHTML is the embedded HTML page
  111. const fileBrowserHTML = `<!DOCTYPE html>
  112. <html lang="zh-CN">
  113. <head>
  114. <meta charset="UTF-8">
  115. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  116. <title>HTTP 文件服务器</title>
  117. <style>
  118. * { margin: 0; padding: 0; box-sizing: border-box; }
  119. body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; }
  120. .container { max-width: 1200px; margin: 0 auto; padding: 20px; }
  121. .header { background: white; border-radius: 12px; padding: 24px; margin-bottom: 20px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); }
  122. .header h1 { font-size: 28px; color: #333; margin-bottom: 8px; }
  123. .header p { color: #888; font-size: 14px; }
  124. .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; }
  125. .breadcrumb a { color: #667eea; text-decoration: none; font-weight: 500; padding: 4px 8px; border-radius: 6px; transition: background 0.2s; }
  126. .breadcrumb a:hover { background: #f0f4ff; }
  127. .breadcrumb span { color: #999; font-size: 20px; }
  128. .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; }
  129. .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; }
  130. .btn-primary { background: linear-gradient(135deg, #667eea, #764ba2); color: white; }
  131. .btn-primary:hover { transform: translateY(-2px); box-shadow: 0 4px 15px rgba(102,126,234,0.4); }
  132. .btn-success { background: #28a745; color: white; }
  133. .btn-success:hover { background: #218838; }
  134. .btn-danger { background: #dc3545; color: white; }
  135. .btn-danger:hover { background: #c82333; }
  136. .btn-sm { padding: 6px 12px; font-size: 12px; }
  137. .file-list { background: white; border-radius: 12px; padding: 24px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); }
  138. table { width: 100%; border-collapse: collapse; }
  139. th, td { padding: 12px 16px; text-align: left; border-bottom: 1px solid #f0f0f0; font-size: 14px; }
  140. th { background: #fafafa; font-weight: 600; color: #555; }
  141. tr:hover { background: #f8f9ff; }
  142. .file-name { display: flex; align-items: center; gap: 8px; }
  143. .file-icon { width: 32px; height: 32px; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 18px; }
  144. .folder-icon { background: #ffeaa7; }
  145. .file-icon-doc { background: #74b9ff; }
  146. .file-icon-img { background: #ff7675; }
  147. .file-icon-zip { background: #a29bfe; }
  148. .file-icon-code { background: #55efc4; }
  149. .file-icon-other { background: #dfe6e9; }
  150. .file-link { color: #667eea; text-decoration: none; font-weight: 500; }
  151. .file-link:hover { text-decoration: underline; }
  152. .actions-cell { display: flex; gap: 8px; }
  153. .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; }
  154. .toast-success { background: #28a745; }
  155. .toast-error { background: #dc3545; }
  156. @keyframes slideIn { from { transform: translateX(100px); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
  157. .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; }
  158. .modal-overlay.show { display: flex; }
  159. .modal { background: white; border-radius: 12px; padding: 30px; width: 480px; max-width: 90%; }
  160. .modal h2 { margin-bottom: 24px; font-size: 20px; }
  161. .modal-actions { display: flex; justify-content: flex-end; gap: 12px; margin-top: 24px; }
  162. .form-group { margin-bottom: 16px; }
  163. .form-group label { display: block; margin-bottom: 6px; font-weight: 600; color: #555; font-size: 14px; }
  164. .form-group input { width: 100%; padding: 10px 14px; border: 1px solid #ddd; border-radius: 6px; font-size: 14px; }
  165. .form-group input:focus { outline: none; border-color: #667eea; }
  166. .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; }
  167. .drop-zone:hover, .drop-zone.dragover { background: #e8ebff; border-color: #764ba2; }
  168. .progress-bar { width: 100%; height: 8px; background: #f0f0f0; border-radius: 4px; overflow: hidden; margin-top: 12px; display: none; }
  169. .progress-bar.show { display: block; }
  170. .progress-fill { height: 100%; background: linear-gradient(135deg, #667eea, #764ba2); transition: width 0.3s; width: 0%; }
  171. .empty-state { text-align: center; padding: 60px 20px; color: #999; }
  172. .empty-state .icon { font-size: 64px; margin-bottom: 16px; }
  173. </style>
  174. </head>
  175. <body>
  176. <div class="container">
  177. <div class="header">
  178. <h1>&#128193; HTTP 文件服务器</h1>
  179. <p>在线浏览、下载文件</p>
  180. </div>
  181. <div class="breadcrumb" id="breadcrumb">
  182. </div>
  183. <div class="actions">
  184. <button class="btn btn-primary" onclick="refresh()">
  185. &#128260; 刷新
  186. </button>
  187. </div>
  188. <div class="file-list">
  189. <table id="fileTable">
  190. <thead>
  191. <tr><th>名称</th><th>大小</th><th>修改时间</th><th>操作</th></tr>
  192. </thead>
  193. <tbody id="fileTableBody">
  194. </tbody>
  195. </table>
  196. <div class="empty-state" id="emptyState" style="display:none">
  197. <div class="icon">&#128193;</div>
  198. <div>目录为空</div>
  199. </div>
  200. </div>
  201. </div>
  202. <script>
  203. let currentPath = '/';
  204. function init() {
  205. loadFiles();
  206. }
  207. function loadFiles() {
  208. fetch('/api/list?path=' + encodeURIComponent(currentPath))
  209. .then(r => r.json())
  210. .then(data => {
  211. const tbody = document.getElementById('fileTableBody');
  212. tbody.innerHTML = '';
  213. if (!data.files || data.files.length === 0) {
  214. document.getElementById('emptyState').style.display = 'block';
  215. document.getElementById('fileTable').style.display = 'none';
  216. return;
  217. }
  218. document.getElementById('emptyState').style.display = 'none';
  219. document.getElementById('fileTable').style.display = 'table';
  220. data.files.forEach(f => {
  221. const tr = document.createElement('tr');
  222. const icon = f.isDir ? '📁' : getFileIcon(f.name);
  223. const iconClass = f.isDir ? 'folder-icon' : 'file-icon-' + getFileType(f.name);
  224. tr.innerHTML = '<td><div class="file-name"><div class="file-icon ' + iconClass + '">' + icon + '</div>' +
  225. (f.isDir ? '<a class="file-link" href="#" onclick="enterFolder(\\'' + escapeStr(f.name) + '\\');return false;">' + f.name + '</a>' : '<span>' + f.name + '</span>') +
  226. '</div></td><td>' + (f.isDir ? '-' : f.size) + '</td><td>' + f.modTime + '</td><td class="actions-cell">' +
  227. (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>') +
  228. '</td></tr>';
  229. tbody.appendChild(tr);
  230. });
  231. updateBreadcrumb();
  232. });
  233. }
  234. function escapeStr(s) {
  235. return s.replace(/\\/g, '\\\\\\\\').replace(/'/g, "\\\\'");
  236. }
  237. function enterFolder(name) {
  238. currentPath = currentPath === '/' ? '/' + name + '/' : currentPath + name + '/';
  239. loadFiles();
  240. }
  241. function updateBreadcrumb() {
  242. const bc = document.getElementById('breadcrumb');
  243. bc.innerHTML = '<a href="#" onclick="goTo(\'/\');return false;">根目录</a>';
  244. const parts = currentPath.split('/').filter(p => p);
  245. let path = '';
  246. parts.forEach(p => {
  247. path += p + '/';
  248. bc.innerHTML += '<span>/</span><a href="#" onclick="goTo(\\'' + path + '\\');return false;">' + p + '</a>';
  249. });
  250. }
  251. function goTo(path) {
  252. currentPath = path;
  253. loadFiles();
  254. }
  255. function refresh() {
  256. loadFiles();
  257. }
  258. function getFileIcon(name) {
  259. const ext = name.split('.').pop().toLowerCase();
  260. const icons = {
  261. 'doc': '📄', 'docx': '📄', 'pdf': '📄', 'txt': '📄',
  262. 'xls': '📊', 'xlsx': '📊', 'csv': '📊',
  263. 'jpg': '🖼️', 'jpeg': '🖼️', 'png': '🖼️', 'gif': '🖼️', 'bmp': '🖼️',
  264. 'mp3': '🎵', 'wav': '🎵', 'flac': '🎵',
  265. 'mp4': '🎬', 'avi': '🎬', 'mkv': '🎬', 'mov': '🎬',
  266. 'zip': '📦', 'rar': '📦', '7z': '📦', 'tar': '📦', 'gz': '📦',
  267. 'js': '💻', 'ts': '💻', 'py': '💻', 'go': '💻', 'java': '💻', 'c': '💻', 'cpp': '💻', 'html': '💻', 'css': '💻', 'json': '💻', 'xml': '💻', 'yml': '💻', 'yaml': '💻',
  268. };
  269. return icons[ext] || '📄';
  270. }
  271. function getFileType(name) {
  272. const ext = name.split('.').pop().toLowerCase();
  273. if (['jpg','jpeg','png','gif','bmp','svg'].includes(ext)) return 'img';
  274. if (['zip','rar','7z','tar','gz'].includes(ext)) return 'zip';
  275. if (['js','ts','py','go','java','c','cpp','html','css','json','xml','yml','yaml'].includes(ext)) return 'code';
  276. return 'doc';
  277. }
  278. function showToast(msg, type) {
  279. const toast = document.createElement('div');
  280. toast.className = 'toast ' + (type === 'error' ? 'toast-error' : 'toast-success');
  281. toast.textContent = msg;
  282. document.body.appendChild(toast);
  283. setTimeout(() => toast.remove(), 3000);
  284. }
  285. init();
  286. </script>
  287. </body>
  288. </html>
  289. `