doujiao9574 2019-04-28 12:12
浏览 124
已采纳

Golang的“ net / http”中的客户端HTTP请求和服务器HTTP请求有什么区别

I have seen people use NewRequest() method of the "net/http" package for testing APIs. Why not use the NewRequest() method from "net/http/httptesting"? What's the difference? Documentation advises the following:

// To generate a client HTTP request instead of a server request, see
// the NewRequest function in the net/http package.

What would be the difference in handling cookies, for example? Both seem to be very similar.

  • 写回答

1条回答 默认 最新

  • dongyuan1970 2019-04-30 13:31
    关注

    TL;DR: they're the same type, used a bit differently for two use cases and initialized differently to serve these use cases


    The difference is only in usage - they are the same type http.Request. http.NewRequest is used for the more "production" use case which is client - "create a new request to send to the server". When writing HTTP servers, it's occasionally useful to create requests for testing, which is what httptest.NewRequest does. The doc of http.NewRequest is helpful here:

    NewRequest returns a Request suitable for use with Client.Do or Transport.RoundTrip. To create a request for use with testing a Server Handler, either use the NewRequest function in the net/http/httptest package, use ReadRequest, or manually update the Request fields. See the Request type's documentation for the difference between inbound and outbound request fields.

    If you check the docs of the http.Request type, you'll find things like:

    // URL specifies either the URI being requested (for server
    // requests) or the URL to access (for client requests).
    //
    // For server requests, the URL is parsed from the URI
    // supplied on the Request-Line as stored in RequestURI.  For
    // most requests, fields other than Path and RawQuery will be
    // empty. (See RFC 7230, Section 5.3)
    //
    // For client requests, the URL's Host specifies the server to
    // connect to, while the Request's Host field optionally
    // specifies the Host header value to send in the HTTP
    // request.
    URL *url.URL
    

    Note the "For client requests" vs. "For server requests".

    If you see a place that doesn't use httptest.NewRequest it could be because:

    1. They're not aware of it
    2. Or they need more careful fine-tuning that http.NewRequest doesn't provide
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?