How to send cacert , cert and key with https request in GoLang?

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

How to send cacert , cert and key with https request in GoLang?

问题

我是你的中文翻译助手,以下是你要翻译的内容:

我对GoLang还不熟悉。有人可以帮我提供GoLang的代码吗,用于执行以下curl请求:

curl -v --cacert ca.crt --cert tls.crt --key tls.key --location --request POST 'https://<.......>' --header 'Content-Type: application/x-www-form-urlencoded'
英文:

I am new to GoLang. Can anyone please help me with the code in GoLang for the following curl request.

curl -v --cacert ca.crt --cert tls.crt --key tls.key --location --request POST &#39;https://&lt;.......&gt;&#39; --header &#39;Content-Type: application/x-www-form-urlencoded&#39;

答案1

得分: 4

https://smallstep.com/hello-mtls/doc/combined/go/go 步骤 5。

这应该可以实现你想要的功能,你只需要指定另一个URL,并在示例中更改文件名。

// ...

caCert, _ := ioutil.ReadFile("ca.crt")
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)

cert, _ := tls.LoadX509KeyPair("client.crt", "client.key")

client := &http.Client{
    Transport: &http.Transport{
        TLSClientConfig: &tls.Config{
            RootCAs:      caCertPool,
            Certificates: []tls.Certificate{cert},
        },
    },
}

// 发起请求
r, err := client.Get("https://myserver.internal.net:9443")

// ...
英文:

From https://smallstep.com/hello-mtls/doc/combined/go/go step 5.

This should do wat you want it to, you just have to specify another URL, and change the file names in the example.

// ...

caCert, _ := ioutil.ReadFile(&quot;ca.crt&quot;)
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)

cert, _ := tls.LoadX509KeyPair(&quot;client.crt&quot;, &quot;client.key&quot;)

client := &amp;http.Client{
    Transport: &amp;http.Transport{
        TLSClientConfig: &amp;tls.Config{
            RootCAs: caCertPool,
            Certificates: []tls.Certificate{cert},
        },
    },
}

// Make a request
r, err := client.Get(&quot;https://myserver.internal.net:9443&quot;)

// ...

huangapple
  • 本文由 发表于 2022年4月15日 13:12:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/71880339.html
匿名

发表评论

匿名网友

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

确定