Mocking HTTPS responses in Go

后端 未结 2 2084
闹比i
闹比i 2021-02-09 15:22

I\'m trying to write tests for a package that makes requests to a web service. I\'m running into issues probably due to my lack of understanding of TLS.

Currently my te

2条回答
  •  执笔经年
    2021-02-09 15:46

    The reason you're getting the error http: TLS handshake error from 127.0.0.1:45678: tls: oversized record received with length 20037 is because https requires a domain name (not an IP Address). Domain names are SSL certificates are assigned to.

    Start the httptest server in TLS mode with your own certs

    cert, err := tls.LoadX509KeyPair("cert.pem", "key.pem")
    if err != nil {
        log.Panic("bad server certs: ", err)
    }
    certs := []tls.Certificate{cert}
    
    server = httptest.NewUnstartedServer(router)
    server.TLS = &tls.Config{Certificates: certs}
    server.StartTLS()
    serverPort = ":" + strings.Split(server.URL, ":")[2] // it's always https://127.0.0.1:
    server.URL = "https://sub.domain.com" + serverPort
    

    To provide a valid SSL certificate for a connection are the options of:

    1. Not supplying a cert and key
    2. Supplying a self-signed cert and key
    3. Supplying a real valid cert and key

    No Cert

    If you don't supply your own cert, then an example.com cert is loaded as default.

    Self-Signed Cert

    To create a testing cert can use the included self-signed cert generator at $GOROOT/src/crypto/tls/generate_cert.go --host "*.domain.name"

    You'll get x509: certificate signed by unknown authority warnings because it's self-signed so you'll need to have your client skip those warnings, by adding the following to your http.Transport field:

     TLSClientConfig: &tls.Config{InsecureSkipVerify: true}
    

    Valid Real Cert

    Finally, if you're going to use a real cert, then save the valid cert and key where they can be loaded.


    The key here is to use server.URL = https://sub.domain.com to supply your own domain.

提交回复
热议问题