英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论