1
0

webservice.go 7.3 KB

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