diff --git a/CHANGELOG.md b/CHANGELOG.md index a5f1dd5..62c66d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # CHANGELOG - go/service +## v1.3.7 (2026-06-02) +- **API 统一**: + - `HostContext` 新增 `Static` 方法,支持 `Host("example.com").Static("/ui", "./dir")` 这种更具一致性的链式调用风格。 + - 全局 `Static` 统一收拢为底层 `Host("*").Static(...)` 实现。 + ## v1.3.6 (2026-05-31) - **基础设施增强**: - 新增 `WebSocketConn` 标准包装器,提供统一的 `Send`, `ReadString`, `ReadBytes`, `ReadJSON` 接口。 diff --git a/README.md b/README.md index 76c35f4..50578e5 100644 --- a/README.md +++ b/README.md @@ -74,7 +74,7 @@ func main() { ``` ### 4. 增强插件 -- **静态文件**: `service.Static("/ui", "./static_dir")` +- **静态文件**: `service.Static("/ui", "./static_dir")` 或 `service.Host("example.com").Static("/ui", "./static_dir")` - **URL 重写**: `service.Rewrite("/old", "/new")` - **反向代理**: `service.Proxy(0, "/api", "other_app", "/api")` - **文档生成**: `service.MakeDocument()` 返回全量接口描述 diff --git a/static.go b/static.go index 8af5352..03e0a0b 100644 --- a/static.go +++ b/static.go @@ -23,8 +23,18 @@ var ( ) // Static 注册静态文件目录 +func (hc *HostContext) Static(path, rootPath string) *HostContext { + host := hc.host + if host == "*" { + host = "" + } + StaticByHost(path, rootPath, host) + return hc +} + +// Static 注册静态文件目录 (使用默认 Host "*") func Static(path, rootPath string) { - StaticByHost(path, rootPath, "") + Host("*").Static(path, rootPath) } // StaticByHost 为指定域名注册静态文件目录 diff --git a/static_test.go b/static_test.go index 8eb330c..14d6574 100644 --- a/static_test.go +++ b/static_test.go @@ -41,3 +41,40 @@ func TestStaticService(t *testing.T) { t.Errorf("Expected 404 for missing file, got %d", w404.Code) } } + +func TestHostStaticService(t *testing.T) { + tempDir, _ := os.MkdirTemp("", "host_static_test") + defer os.RemoveAll(tempDir) + + testFile := filepath.Join(tempDir, "index.html") + _ = os.WriteFile(testFile, []byte("

Host Static Page

"), 0644) + + // 注册域名特定静态文件服务 + Host("example.com").Static("/host-ui", tempDir) + + rh := &RouteHandler{} + + // 1. 匹配域名访问 + req1 := httptest.NewRequest("GET", "/host-ui/index.html", nil) + req1.Host = "example.com" + w1 := httptest.NewRecorder() + rh.ServeHTTP(w1, req1) + + if w1.Code != http.StatusOK { + t.Errorf("Expected 200, got %d", w1.Code) + } + if body := w1.Body.String(); body != "

Host Static Page

" { + t.Errorf("Content mismatch: %s", body) + } + + // 2. 不匹配域名访问 (应该 404) + req2 := httptest.NewRequest("GET", "/host-ui/index.html", nil) + req2.Host = "other.com" + w2 := httptest.NewRecorder() + rh.ServeHTTP(w2, req2) + + if w2.Code != http.StatusNotFound { + t.Errorf("Expected 404 for mismatched host, got %d", w2.Code) + } +} +