webservice.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. // ============================================================================
  2. //go:build !service
  3. // webservice.go — 工具页 Web 服务
  4. //
  5. // 选择任意目录开启本地静态文件浏览服务;readme.md 自动渲染为 HTML;
  6. // 支持端口自动探测与运行状态查询。
  7. // ============================================================================
  8. package main
  9. import (
  10. "context"
  11. "encoding/json"
  12. "errors"
  13. "fmt"
  14. "net"
  15. "net/http"
  16. "os"
  17. "path/filepath"
  18. "strings"
  19. "sync"
  20. "time"
  21. "github.com/gomarkdown/markdown"
  22. )
  23. // WebServiceInfo 描述一次 Web 服务运行实例的状态,供前端展示。
  24. type WebServiceInfo struct {
  25. Running bool `json:"running"` // 是否运行中
  26. Dir string `json:"dir"` // 服务目录
  27. URL string `json:"url"` // 访问地址 http://127.0.0.1:port/
  28. Port int `json:"port"` // 监听端口
  29. IndexName string `json:"indexName"` // 实际用作默认页的文件(index.html / readme.md / 空)
  30. StartedAt string `json:"startedAt"` // 启动时间
  31. Error string `json:"error"` // 最近一次错误
  32. Connections int64 `json:"connections"` // 累计请求次数
  33. }
  34. // webService 持有静态文件服务的运行状态(全局单例,工具页调用)。
  35. type webService struct {
  36. mu sync.Mutex
  37. server *http.Server
  38. dir string
  39. url string
  40. port int // 监听端口
  41. index string // 默认页文件名
  42. started time.Time
  43. conns int64
  44. }
  45. var webSrv = &webService{}
  46. // websvcEmit 推送一条日志给前端信息框。kind: req / info。
  47. func websvcEmit(kind, line string) {
  48. if app == nil {
  49. return
  50. }
  51. app.Event.Emit("websvc:log", map[string]string{"kind": kind, "line": line})
  52. }
  53. // pickWebDir 弹出目录选择对话框,返回用户选中的目录(取消则返回空串)。
  54. // 使用 Wails 全局 app 的 Dialog(绑定到主窗口)。
  55. func pickWebDir() (string, error) {
  56. if app == nil {
  57. return "", errors.New("应用未初始化")
  58. }
  59. dialog := app.Dialog.OpenFile().
  60. CanChooseDirectories(true).
  61. CanChooseFiles(false).
  62. SetTitle("选择要浏览的目录")
  63. return dialog.PromptForSingleSelection()
  64. }
  65. // resolveIndexName 判断目录默认页:优先 index.html,其次 readme.md(或 README.md)。
  66. func resolveIndexName(dir string) string {
  67. if fileExists(filepath.Join(dir, "index.html")) {
  68. return "index.html"
  69. }
  70. for _, name := range []string{"readme.md", "README.md", "Readme.md"} {
  71. if fileExists(filepath.Join(dir, name)) {
  72. return name
  73. }
  74. }
  75. return ""
  76. }
  77. func fileExists(path string) bool {
  78. st, err := os.Stat(path)
  79. return err == nil && !st.IsDir()
  80. }
  81. // webHandler 提供静态文件服务,并对「默认页」做兜底:
  82. // 请求根路径时,若无 index.html 但有 readme.md,则渲染 README 为 HTML。
  83. func webHandler(dir, indexName string) http.Handler {
  84. // 仅当 README 是默认页且无 index.html 时,才用自定义处理器(渲染 Markdown)
  85. if indexName != "" && !strings.EqualFold(indexName, "index.html") {
  86. readmePath := filepath.Join(dir, indexName)
  87. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  88. if r.URL.Path == "/" || r.URL.Path == "" {
  89. data, err := os.ReadFile(readmePath)
  90. if err != nil {
  91. http.Error(w, "readme.md 读取失败: "+err.Error(), http.StatusInternalServerError)
  92. return
  93. }
  94. html := markdown.ToHTML(data, nil, nil)
  95. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  96. w.Write(html)
  97. return
  98. }
  99. // 非根路径:交给默认文件服务器(提供子目录/静态资源)
  100. http.FileServer(http.Dir(dir)).ServeHTTP(w, r)
  101. })
  102. }
  103. // 有 index.html(或两者都无):用标准文件服务器,浏览器自动服务 index.html 或目录列表
  104. return http.FileServer(http.Dir(dir))
  105. }
  106. // StartWebService 启动静态文件服务,监听 127.0.0.1:port(port 可指定,0 表示随机端口)。
  107. // 若已运行则先停止旧实例。indexName 为空时自动探测默认页。
  108. func StartWebService(dir string, port int) (WebServiceInfo, error) {
  109. if strings.TrimSpace(dir) == "" {
  110. return WebServiceInfo{}, errors.New("目录不能为空")
  111. }
  112. if port < 0 || port > 65535 {
  113. return WebServiceInfo{}, fmt.Errorf("端口无效: %d(范围 1-65535)", port)
  114. }
  115. st, err := os.Stat(dir)
  116. if err != nil || !st.IsDir() {
  117. return WebServiceInfo{}, fmt.Errorf("目录不存在或不是文件夹: %s", dir)
  118. }
  119. indexName := resolveIndexName(dir)
  120. // 先停止已有实例(幂等)
  121. stopWebService()
  122. addr := fmt.Sprintf("127.0.0.1:%d", port)
  123. ln, err := net.Listen("tcp", addr)
  124. if err != nil {
  125. return WebServiceInfo{}, fmt.Errorf("监听端口 %d 失败(可能被占用): %w", port, err)
  126. }
  127. actualPort := ln.Addr().(*net.TCPAddr).Port
  128. mux := http.NewServeMux()
  129. handler := webHandler(dir, indexName)
  130. mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  131. start := time.Now()
  132. sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
  133. handler.ServeHTTP(sw, r)
  134. webSrv.mu.Lock()
  135. webSrv.conns++
  136. webSrv.mu.Unlock()
  137. websvcEmit("req", fmt.Sprintf("%s %s %s %s %s %d %s",
  138. time.Now().Format("15:04:05"),
  139. r.Method, r.URL.Path, r.RemoteAddr, r.Proto, sw.status, time.Since(start).Round(time.Millisecond)))
  140. }))
  141. srv := &http.Server{Handler: mux}
  142. webSrv.mu.Lock()
  143. webSrv.server = srv
  144. webSrv.dir = dir
  145. webSrv.port = actualPort
  146. webSrv.url = fmt.Sprintf("http://127.0.0.1:%d/", actualPort)
  147. webSrv.index = indexName
  148. webSrv.started = time.Now()
  149. webSrv.conns = 0
  150. webSrv.mu.Unlock()
  151. go func() {
  152. _ = srv.Serve(ln) // 阻塞直到 Shutdown;返回 http.ErrServerClosed 属正常
  153. }()
  154. websvcEmit("info", fmt.Sprintf("%s Web 服务已启动: http://127.0.0.1:%d/ (目录: %s)",
  155. time.Now().Format("15:04:05"), actualPort, dir))
  156. return WebServiceInfo{
  157. Running: true, Dir: dir, URL: webSrv.url, Port: actualPort, IndexName: indexName,
  158. StartedAt: webSrv.started.Format("2006-01-02 15:04:05"),
  159. }, nil
  160. }
  161. // statusWriter 包装 ResponseWriter 以捕获响应状态码(用于请求日志)。
  162. type statusWriter struct {
  163. http.ResponseWriter
  164. status int
  165. }
  166. // WriteHeader 记录写入的状态码。
  167. func (w *statusWriter) WriteHeader(code int) {
  168. w.status = code
  169. w.ResponseWriter.WriteHeader(code)
  170. }
  171. // StopWebService 停止当前静态文件服务(未运行则无副作用)。
  172. func StopWebService() {
  173. stopWebService()
  174. }
  175. func stopWebService() {
  176. webSrv.mu.Lock()
  177. wasRunning := webSrv.server != nil
  178. if webSrv.server != nil {
  179. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  180. _ = webSrv.server.Shutdown(ctx)
  181. cancel()
  182. webSrv.server = nil
  183. webSrv.url = ""
  184. webSrv.dir = ""
  185. webSrv.index = ""
  186. webSrv.port = 0
  187. }
  188. webSrv.mu.Unlock()
  189. if wasRunning {
  190. websvcEmit("info", fmt.Sprintf("%s Web 服务已停止", time.Now().Format("15:04:05")))
  191. }
  192. }
  193. // WebServiceStatus 返回当前 Web 服务状态。
  194. func WebServiceStatus() WebServiceInfo {
  195. webSrv.mu.Lock()
  196. defer webSrv.mu.Unlock()
  197. info := WebServiceInfo{
  198. Running: webSrv.server != nil, Dir: webSrv.dir, URL: webSrv.url,
  199. Port: webSrv.port, IndexName: webSrv.index, Connections: webSrv.conns,
  200. }
  201. if !webSrv.started.IsZero() {
  202. info.StartedAt = webSrv.started.Format("2006-01-02 15:04:05")
  203. }
  204. return info
  205. }
  206. // WebServiceJSON 为前端提供一次调用获取完整状态的辅助(避免多次 IPC)。
  207. func WebServiceJSON() string {
  208. b, _ := json.Marshal(WebServiceStatus())
  209. return string(b)
  210. }