Created
March 22, 2024 00:50
-
-
Save chzealot/1fdffaafd2f5eecc3b04d5de2b5d9535 to your computer and use it in GitHub Desktop.
create http client with custom root ca
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/tls" | |
"crypto/x509" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"os" | |
) | |
func main() { | |
// get root ca file: https://curl.se/docs/caextract.html | |
content, err := os.ReadFile("/tmp/cacert-2024-03-11.pem") | |
if err != nil { | |
log.Fatal(err) | |
} | |
// rootCaContent 包含你的自定义根证书内容 | |
var rootCaContent = content | |
// 创建一个新的CertPool,并尝试添加rootCaContent证书 | |
roots := x509.NewCertPool() | |
ok := roots.AppendCertsFromPEM([]byte(rootCaContent)) | |
if !ok { | |
panic("failed to parse root certificate") | |
} | |
// 创建一个TLS配置,使用我们的根证书 | |
tlsConfig := &tls.Config{ | |
RootCAs: roots, | |
} | |
// 创建一个HTTP客户端,使用自定义的TLS配置 | |
client := &http.Client{ | |
Transport: &http.Transport{ | |
TLSClientConfig: tlsConfig, | |
}, | |
} | |
// 使用这个客户端发起请求 | |
response, err := client.Get("https://google.com") | |
if err != nil { | |
panic(err) | |
} | |
defer response.Body.Close() | |
// 读取响应内容 | |
body, err := ioutil.ReadAll(response.Body) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Printf("code: %d\nbody:\n%s\n", response.StatusCode, body) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment