server.go 13 KB

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