多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] ## 语法 ``` func NewRequest(method, target string, body io.Reader) *http.Request type ResponseRecorder func NewRecorder() *ResponseRecorder func (rw *ResponseRecorder) Flush() func (rw *ResponseRecorder) Header() http.Header func (rw *ResponseRecorder) Result() *http.Response func (rw *ResponseRecorder) Write(buf []byte) (int, error) func (rw *ResponseRecorder) WriteHeader(code int) func (rw *ResponseRecorder) WriteString(str string) (int, error) type Server func NewServer(handler http.Handler) *Server func NewTLSServer(handler http.Handler) *Server func NewUnstartedServer(handler http.Handler) *Server func (s *Server) Certificate() *x509.Certificate func (s *Server) Client() *http.Client func (s *Server) Close() func (s *Server) CloseClientConnections() func (s *Server) Start() func (s *Server) StartTLS() ``` ## 示例 ### httptest.NewRequest 创建请求头 ``` httptest.NewRequest("GET","http://127.0.0.1/foo",nil) ``` ### 两种模拟http 服务器的方式 #### 访问模拟的server ``` func Api(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "hello world") } // test func TestApi(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(Api)) defer server.Close() res, err := http.Get(server.URL) if err != nil { t.Log(err) } all, err := ioutil.ReadAll(res.Body) if err != nil { t.Log(err) } if string(all) != "hello world" { t.Error("返回值不正确") } } ``` #### Recorder ``` func Api(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "hello world") } // test func TestApi(t *testing.T) { // 域名可以随便写,参数可以按照实际需求写 req := httptest.NewRequest("GET", "http://127.0.0.1:8010/foo", nil) recorder := httptest.NewRecorder() Api(recorder, req) all, err := ioutil.ReadAll(recorder.Body) if err != nil { t.Error(err) } t.Log(string(all)) } ``` ### http2 查看官方的 httptest 的 example_test.go ### 支持 TLS 查看官方的 httptest 的 example_test.go