在Golang项目里,端口与网络测试常常决定接口的可靠性。借助标准库net/http与httptest,开发者可以在不依赖外部运行环境的情况下,完成服务端逻辑验证与客户端请求模拟。

使用httptest启动测试服务器
httptest包能够创建一个临时HTTP服务器,自动分配可用端口,非常适合单元测试。下面的例子展示如何编写一个简单的测试服务并发送请求。
package main
import (
"io"
"net/http"
"net/http/httptest"
"testing"
)
func TestServer(t *testing.T) {
// 使用httptest创建测试服务器
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
io.WriteString(w, "hello")
}))
defer srv.Close()
// 通过srv.URL获取分配好的地址与端口
resp, err := http.Get(srv.URL)
if err != nil {
t.Fatalf("请求失败: %v", err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
if string(body) != "hello" {
t.Fatalf("响应内容错误: %s", body)
}
}
检查本地端口是否被占用
有时需要确认某个端口是否空闲,可以用net包尝试监听。若返回错误则说明端口已被使用。
package main
import (
"fmt"
"net"
)
func isPortFree(port string) bool {
// 尝试监听TCP端口
listener, err := net.Listen("tcp", ":"+port)
if err != nil {
return false
}
listener.Close()
return true
}
func main() {
if isPortFree("8080") {
fmt.Println("端口8080可用")
} else {
fmt.Println("端口8080被占用")
}
}
使用net/http进行客户端网络测试
除了服务端,客户端请求也需要测试。可以自定义http.Client并设置超时,避免测试卡死。
package main
import (
"net/http"
"time"
)
func requestWithTimeout(url string) (*http.Response, error) {
client := &http.Client{
Timeout: 2 * time.Second,
}
return client.Get(url)
}
常见注意事项
- httptest服务器默认使用随机端口,不要硬编码端口号。
- 测试结束必须调用Close方法释放资源。
- 在并发测试中,每个用例应使用独立服务器实例。
小结
通过httptest与net/http组合,Golang开发者能高效完成端口与网络测试,既保证代码质量,也降低联调成本。