在微服务的调试过程中,我想知道我的客户端服务请求最终是什么样子,以确保是客户端服务的问题还是目标服务的问题。
为此,我需要一个工具(或 pkg)将
http.Request
结构转换为 cURL 命令
http.Request 结构示例:
{
Method:POST
URL:https://some-fake-url.com
Proto:HTTP/1.1
ProtoMajor:1
ProtoMinor:1
Accept-Encoding:[gzip, deflate, br]
Accept-Language:[en-US,en;q=0.9]
Authorization:[Bearer gkasgjagsljkg]
Connection:[keep-alive]
Content-Length:[0]
Content-Type:[application/json]
...
}
客户端服务使用此请求
http.DefaultClient.Do()
,
我不想手动将其转换为 cURL,因为这可能无效。
您可以使用 http2curl pkg 将 Golang 请求转换为 cURL 命令,如下所示:
import (
"http"
"moul.io/http2curl"
)
data := bytes.NewBufferString(`{"hello":"world","answer":42}`)
req, _ := http.NewRequest("PUT", "http://www.example.com/abc/def.ghi?jlk=mno&pqr=stu", data)
req.Header.Set("Content-Type", "application/json")
command, _ := http2curl.GetCurlCommand(req)
fmt.Println(command)
// Output: curl -X PUT -d "{\"hello\":\"world\",\"answer\":42}" -H "Content-Type: application/json" http://www.example.com/abc/def.ghi?jlk=mno&pqr=stu
您也可以使用套餐curling
package main
import (
"fmt"
"log"
"net/http"
"github.com/aoliveti/curling"
)
func main() {
req, err := http.NewRequest(http.MethodGet, "https://www.google.com", nil)
if err != nil {
log.Fatal(err)
}
req.Header.Add("If-None-Match", "foo")
cmd, err := curling.NewFromRequest(req)
if err != nil {
log.Fatal(err)
}
fmt.Println(cmd)
}
输出
curl -X 'GET' 'https://www.google.com' -H 'If-None-Match: foo'