Home >Backend Development >Golang >How to Handle HTTPS Requests with Custom or Untrusted Certificates in Go?

How to Handle HTTPS Requests with Custom or Untrusted Certificates in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-11 12:05:10647browse

How to Handle HTTPS Requests with Custom or Untrusted Certificates in Go?

Sending HTTPS Requests with Certificates in Go

When interacting with HTTPS services that require certificate verification, developers may encounter errors related to不知名的授权机构. To overcome this issue, Go provides a mechanism to validate server certificates using trusted CA certificates.

To solve the problem, you need to obtain the CA certificate of the trusted authority that issued the server certificate. Once you have the CA certificate, you can add it to the transport layer of your HTTP client as shown below:

import (
    "crypto/tls"
    "io/ioutil"
    "log"
    "net/http"
    "crypto/x509"
)

func main() {
    caCert, err := ioutil.ReadFile("rootCA.crt")
    if err != nil {
        log.Fatal(err)
    }
    caCertPool := x509.NewCertPool()
    caCertPool.AppendCertsFromPEM(caCert)

    client := &http.Client{
        Transport: &http.Transport{
            TLSClientConfig: &tls.Config{
                RootCAs:      caCertPool,
            },
        },
    }

    _, err := client.Get("https://secure.domain.com")
    if err != nil {
        panic(err)
    }
}

Additionally, you can generate a custom CA certificate and sign your own certificates for secure communication. The following steps outline how to create your own CA and certificate for a specific domain:

  1. Generate CA:

    openssl genrsa -out rootCA.key 4096
    openssl req -x509 -new -key rootCA.key -days 3650 -out rootCA.crt
  2. Generate Certificate for Domain:

    openssl genrsa -out secure.domain.com.key 2048
    openssl req -new -key secure.domain.com.key -out secure.domain.com.csr
    openssl x509 -req -in secure.domain.com.csr -CA rootCA.crt -CAkey rootCA.key -CAcreateserial -days 365 -out secure.domain.com.crt

By following these steps, you can verify server certificates and establish secure HTTPS connections in your Go applications.

The above is the detailed content of How to Handle HTTPS Requests with Custom or Untrusted Certificates in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn