2019-04-28 12:12 阅读 59

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 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
    点赞 评论 复制链接分享