直接给个例子,方便日常开发接口请求
创建个测试文体
vim test/test_request.go
编辑一下代码
package testimport ("io/ioutil""net/http""net/http/httptest""testing"
)func TestCustomClient(t *testing.T) {// 创建一个模拟的 HTTP 服务器server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {// 设置响应头w.Header().Set("Content-Type", "application/json") // 必须在 WriteHeader 和 Write 之前调用// 设置响应状态码w.WriteHeader(http.StatusOK)// 返回响应内容w.Write([]byte(`{"message": "Hi! golang"}`))}))defer server.Close() // 测试结束后关闭服务器// 发起请求到模拟的服务器resp, err := http.Get(server.URL)if err != nil {t.Fatalf("请求失败: %v", err)}defer resp.Body.Close()// 检查响应状态码if resp.StatusCode != http.StatusOK {t.Errorf("期望状态码 200,实际得到 %d", resp.StatusCode)}// 检查响应头contentType := resp.Header.Get("Content-Type")if contentType != "application/json" {t.Errorf("期望 Content-Type 为 application/json,实际得到 %s", contentType)}// 读取响应体body, err := ioutil.ReadAll(resp.Body)if err != nil {t.Fatalf("读取响应体失败: %v", err)}// 检查响应内容expectedBody := `{"message": "Hi! golang!"}`if string(body) != expectedBody {t.Errorf("期望响应体 %s,实际得到 %s", expectedBody, string(body))}
}
进行测试验证
go test test_request.go
正常通过显示如下:
% go test test/request_test.go
ok command-line-arguments 0.536s