使用net/http提供静态文件服务,通过http.StripPrefix将/static/映射到assets目录。2. 编写单元测试用httptest模拟GET请求,验证状态码和响应内容。3. 测试404情况确保未找到文件时返回正确状态码。4. 注意测试环境可移植性及Go 1.16+ embed特性适配,提升服务可靠性。

在Go语言开发中,Web应用常需要提供静态资源服务,比如CSS、JavaScript、图片等文件。为了确保静态资源能被正确访问,编写单元测试是保障服务稳定的重要手段。下面通过一个简单示例展示如何为Golang Web项目中的静态资源处理编写单元测试。
使用net/http包可以轻松提供静态文件服务。以下是一个简单的HTTP服务器,将/static/路径映射到本地的assets目录:
package main
import (
"net/http"
)
func main() {
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("assets"))))
http.ListenAndServe(":8080", nil)
}
假设项目结构如下:
project/
├── main.go
└── assets/
└── style.css
访问 http://localhost:8080/static/style.css 就能获取该CSS文件。
立即学习“go语言免费学习笔记(深入)”;
我们可以使用net/http/httptest包来测试静态文件是否能被正确返回。以下是一个测试用例,验证style.css能否成功加载:
package main
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestStaticFileServer(t *testing.T) {
req := httptest.NewRequest("GET", "/static/style.css", nil)
w := httptest.NewRecorder()
handler := http.FileServer(http.Dir("assets"))
http.StripPrefix("/static/", handler).ServeHTTP(w, req)
resp := w.Result()
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("期望状态码 %d,实际得到 %d", http.StatusOK, resp.StatusCode)
}
body, _ := io.ReadAll(resp.Body)
if !strings.Contains(string(body), "body") {
t.Error("期望CSS内容包含 'body',但未找到")
}
}
说明:
除了正常情况,也应测试无效路径是否返回404:
func TestStaticFileNotFound(t *testing.T) {
req := httptest.NewRequest("GET", "/static/notexist.txt", nil)
w := httptest.NewRecorder()
handler := http.FileServer(http.Dir("assets"))
http.StripPrefix("/static/", handler).ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Errorf("期望状态码 %d,实际得到 %d", http.StatusNotFound, w.Code)
}
}
这个测试确保当请求不存在的文件时,服务器返回404状态码。
以上就是Golang单元测试Web静态资源处理示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号