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
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)