根据组成部分构建HTTP请求。

huangapple go评论93阅读模式
英文:

Build HTTP request based on constituent parts

问题

假设我有一个将HTTP请求拆分为以下部分的表示形式:方法、URI、查询参数、标头、正文。

所以我可能有这样的内容:

方法:POST
标头:[Content-Type: application/json, Host: localhost:8080, 等等...]
路径:/home/sweet
查询:name=dan&id=1
正文:"这里是一些JSON"

如何将其重建为有效的net/http请求对象?我希望尽可能避免使用字符串格式化和构建。

英文:

Say I have a representation of an HTTP request broken down to parts like so: method, URI, query params, headers, body.

So I might have something like:

Method: POST
Headers: [Content-Type: application/json, Host: localhost:8080, etc...]
Path: /home/sweet
Query: name=dan&id=1
Body: "some JSON here"

How can I rebuild this into a valid net/http Request object? I would like to avoid string formatting and building as much as possible.

答案1

得分: 4

创建http.Request的唯一方法是使用http.NewRequest。它已经将你的三个组成部分作为参数传入:方法(Method)、路径(path)和消息体(body)。

在调用NewRequest之前,你需要将查询参数组装到URL中。url包,特别是url.Values可能对此有所帮助。

一旦你有了新的请求,你可以像预期的那样添加头部信息:

req, err := http.NewRequest("GET", "http://example.com/?foo=bar", body)
req.Header.Add("Content-Type", "application/json")

需要说明的是,消息体必须是一个io.Reader,但这给了你完全的灵活性。

英文:

There's really only one way to create an http.Request, and that is with http.NewRequest. And it already takes three of your constituent parts as arguments: Method, path, and body.

You'll need to assemble your query params into the URL before calling NewRequest. The url package, and in particular, url.Values may be of assistance with this.

Once you have the new request, you can add headers as you would expect:

req, err := http.NewRequest("GET", "http://example.com/?foo=bar", body)
req.Header.Add("Content-Type", "application/json")

And in case it needs stating, the body must be an io.Reader, but that gives you complete flexibility.

huangapple
  • 本文由 发表于 2017年3月31日 23:31:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/43144508.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定