How to use GetTLSClientConfig method of httpmultibin Package

Best K6 code snippet using httpmultibin.GetTLSClientConfig

httpmultibin.go

Source:httpmultibin.go Github

copy

Full Screen

...44 "github.com/stretchr/testify/assert"45 "github.com/stretchr/testify/require"46 "golang.org/x/net/http2"47)48// GetTLSClientConfig returns a TLS config that trusts the supplied49// httptest.Server certificate as well as all the system root certificates50func GetTLSClientConfig(t testing.TB, srv *httptest.Server) *tls.Config {51 var err error52 certs := x509.NewCertPool()53 if runtime.GOOS != "windows" {54 certs, err = x509.SystemCertPool()55 require.NoError(t, err)56 }57 for _, c := range srv.TLS.Certificates {58 roots, err := x509.ParseCertificates(c.Certificate[len(c.Certificate)-1])59 require.NoError(t, err)60 for _, root := range roots {61 certs.AddCert(root)62 }63 }64 return &tls.Config{65 RootCAs: certs,66 InsecureSkipVerify: false,67 Renegotiation: tls.RenegotiateFreelyAsClient,68 }69}70const httpDomain = "httpbin.local"71// We have to use example.com if we want a real HTTPS domain with a valid72// certificate because the default httptest certificate is for example.com:73// https://golang.org/src/net/http/internal/testcert.go?s=399:410#L1074const httpsDomain = "example.com"75// HTTPMultiBin can be used as a local alternative of httpbin.org. It offers both http and https servers, as well as real domains76type HTTPMultiBin struct {77 Mux *http.ServeMux78 ServerHTTP *httptest.Server79 ServerHTTPS *httptest.Server80 Replacer *strings.Replacer81 TLSClientConfig *tls.Config82 Dialer *netext.Dialer83 HTTPTransport *http.Transport84 Context context.Context85 Cleanup func()86}87type jsonBody struct {88 Header http.Header `json:"headers"`89 Compression string `json:"compression"`90}91func getWebsocketHandler(echo bool, closePrematurely bool) http.Handler {92 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {93 conn, err := (&websocket.Upgrader{}).Upgrade(w, req, w.Header())94 if err != nil {95 return96 }97 if echo {98 messageType, r, e := conn.NextReader()99 if e != nil {100 return101 }102 var wc io.WriteCloser103 wc, err = conn.NextWriter(messageType)104 if err != nil {105 return106 }107 if _, err = io.Copy(wc, r); err != nil {108 return109 }110 if err = wc.Close(); err != nil {111 return112 }113 }114 // closePrematurely=true mimics an invalid WS server that doesn't115 // send a close control frame before closing the connection.116 if !closePrematurely {117 closeMsg := websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")118 _ = conn.WriteControl(websocket.CloseMessage, closeMsg, time.Now().Add(time.Second))119 // Wait for response control frame120 <-time.After(time.Second)121 }122 err = conn.Close()123 if err != nil {124 return125 }126 })127}128func writeJSON(w io.Writer, v interface{}) error {129 e := json.NewEncoder(w)130 e.SetIndent("", " ")131 return errors.Wrap(e.Encode(v), "failed to encode JSON")132}133func getEncodedHandler(t testing.TB, compressionType httpext.CompressionType) http.Handler {134 return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {135 var (136 encoding string137 err error138 encw io.WriteCloser139 )140 switch compressionType {141 case httpext.CompressionTypeBr:142 encw = brotli.NewWriter(rw)143 encoding = "br"144 case httpext.CompressionTypeZstd:145 encw, _ = zstd.NewWriter(rw)146 encoding = "zstd"147 }148 rw.Header().Set("Content-Type", "application/json")149 rw.Header().Add("Content-Encoding", encoding)150 data := jsonBody{151 Header: req.Header,152 Compression: encoding,153 }154 err = writeJSON(encw, data)155 if encw != nil {156 _ = encw.Close()157 }158 if !assert.NoError(t, err) {159 return160 }161 })162}163func getZstdBrHandler(t testing.TB) http.Handler {164 return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {165 encoding := "zstd, br"166 rw.Header().Set("Content-Type", "application/json")167 rw.Header().Add("Content-Encoding", encoding)168 data := jsonBody{169 Header: req.Header,170 Compression: encoding,171 }172 bw := brotli.NewWriter(rw)173 zw, _ := zstd.NewWriter(bw)174 defer func() {175 _ = zw.Close()176 _ = bw.Close()177 }()178 require.NoError(t, writeJSON(zw, data))179 })180}181// NewHTTPMultiBin returns a fully configured and running HTTPMultiBin182func NewHTTPMultiBin(t testing.TB) *HTTPMultiBin {183 // Create a http.ServeMux and set the httpbin handler as the default184 mux := http.NewServeMux()185 mux.Handle("/brotli", getEncodedHandler(t, httpext.CompressionTypeBr))186 mux.Handle("/ws-echo", getWebsocketHandler(true, false))187 mux.Handle("/ws-echo-invalid", getWebsocketHandler(true, true))188 mux.Handle("/ws-close", getWebsocketHandler(false, false))189 mux.Handle("/ws-close-invalid", getWebsocketHandler(false, true))190 mux.Handle("/zstd", getEncodedHandler(t, httpext.CompressionTypeZstd))191 mux.Handle("/zstd-br", getZstdBrHandler(t))192 mux.Handle("/", httpbin.New().Handler())193 // Initialize the HTTP server and get its details194 httpSrv := httptest.NewServer(mux)195 httpURL, err := url.Parse(httpSrv.URL)196 require.NoError(t, err)197 httpIP := net.ParseIP(httpURL.Hostname())198 require.NotNil(t, httpIP)199 // Initialize the HTTPS server and get its details and tls config200 httpsSrv := httptest.NewTLSServer(mux)201 httpsURL, err := url.Parse(httpsSrv.URL)202 require.NoError(t, err)203 httpsIP := net.ParseIP(httpsURL.Hostname())204 require.NotNil(t, httpsIP)205 tlsConfig := GetTLSClientConfig(t, httpsSrv)206 // Set up the dialer with shorter timeouts and the custom domains207 dialer := netext.NewDialer(net.Dialer{208 Timeout: 2 * time.Second,209 KeepAlive: 10 * time.Second,210 DualStack: true,211 })212 dialer.Hosts = map[string]net.IP{213 httpDomain: httpIP,214 httpsDomain: httpsIP,215 }216 // Pre-configure the HTTP client transport with the dialer and TLS config (incl. HTTP2 support)217 transport := &http.Transport{218 DialContext: dialer.DialContext,219 TLSClientConfig: tlsConfig,...

Full Screen

Full Screen

GetTLSClientConfig

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 caCert, err := ioutil.ReadFile("cert.pem")4 if err != nil {5 fmt.Println("Error: ", err)6 }7 caCertPool := x509.NewCertPool()8 caCertPool.AppendCertsFromPEM(caCert)9 tlsConfig := &tls.Config{10 }11 tlsConfig.BuildNameToCertificate()12 tlsConfig.GetClientCertificate = func(info *tls.CertificateRequestInfo) (*tls.Certificate, error) {13 cert, err := tls.LoadX509KeyPair("cert.pem", "key.pem")14 if err != nil {15 fmt.Println("Error: ", err)16 }17 }18 tlsConfig.BuildNameToCertificate()19 transport := &http.Transport{TLSClientConfig: tlsConfig}20 client := &http.Client{Transport: transport}21 if err != nil {22 fmt.Println("Error: ", err)23 }24 resp, err := client.Do(req)25 if err != nil {26 fmt.Println("Error: ", err)27 }28 defer resp.Body.Close()29 body, err := ioutil.ReadAll(resp.Body)30 if err != nil {31 fmt.Println("Error: ", err)32 }33 fmt.Println(string(body))34}

Full Screen

Full Screen

GetTLSClientConfig

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 caCert, err := ioutil.ReadFile("cert.pem")4 if err != nil {5 fmt.Println("Error reading cert.pem")6 }7 caCertPool := x509.NewCertPool()8 caCertPool.AppendCertsFromPEM(caCert)9 tlsConfig := &tls.Config{10 }11 tlsConfig.BuildNameToCertificate()12 transport := &http.Transport{TLSClientConfig: tlsConfig}13 client := &http.Client{Transport: transport}14 if err != nil {15 fmt.Println(err)16 }17 resp, err := client.Do(req)18 if err != nil {19 fmt.Println(err)20 }21 defer resp.Body.Close()22 fmt.Println(resp.Status)23}24import (25func main() {26 caCert, err := ioutil.ReadFile("cert.pem")27 if err != nil {28 fmt.Println("Error reading cert.pem")29 }30 caCertPool := x509.NewCertPool()31 caCertPool.AppendCertsFromPEM(caCert)32 tlsConfig := &tls.Config{33 }34 tlsConfig.BuildNameToCertificate()35 transport := &http.Transport{TLSClientConfig: tlsConfig}

Full Screen

Full Screen

GetTLSClientConfig

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 http.DefaultTransport.(*http.Transport).TLSClientConfig = httpmultibin.GetTLSClientConfig()4 if err != nil {5 fmt.Println(err)6 }7 defer resp.Body.Close()8 body, err := ioutil.ReadAll(resp.Body)9 fmt.Println(string(body))10}11import (12func main() {13 http.DefaultTransport.(*http.Transport).TLSClientConfig = httpmultibin.GetTLSClientConfig()14 if err != nil {15 fmt.Println(err)16 }17 defer resp.Body.Close()18 body, err := ioutil.ReadAll(resp.Body)19 fmt.Println(string(body))20}21import (22func main() {23 http.DefaultTransport.(*http.Transport).TLSClientConfig = httpmultibin.GetTLSClientConfig()24 if err != nil {25 fmt.Println(err)26 }27 defer resp.Body.Close()28 body, err := ioutil.ReadAll(resp.Body)29 fmt.Println(string(body))30}31import (32func main() {33 http.DefaultTransport.(*http.Transport).TLSClientConfig = httpmultibin.GetTLSClientConfig()34 if err != nil {35 fmt.Println(err)36 }37 defer resp.Body.Close()38 body, err := ioutil.ReadAll(resp.Body)39 fmt.Println(string(body))40}41import (

Full Screen

Full Screen

GetTLSClientConfig

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 config := httptest.GetTLSClientConfig()4 client := &http.Client{5 Transport: &http.Transport{6 },7 }8 req, err := http.NewRequest("GET", url, nil)9 if err != nil {10 fmt.Printf("Error creating HTTP request: %v", err)11 os.Exit(1)12 }13 resp, err := client.Do(req)14 if err != nil {15 fmt.Printf("Error sending HTTP request: %v", err)16 os.Exit(1)17 }18 defer resp.Body.Close()19 body, err := ioutil.ReadAll(resp.Body)20 if err != nil {21 fmt.Printf("Error reading HTTP response: %v", err)22 os.Exit(1)23 }24 fmt.Printf("%s", body)25}

Full Screen

Full Screen

GetTLSClientConfig

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 caCert, err := ioutil.ReadFile("ca.pem")4 if err != nil {5 log.Fatal(err)6 }7 caCertPool := x509.NewCertPool()8 caCertPool.AppendCertsFromPEM(caCert)9 client := http.Client{10 Transport: &http.Transport{11 TLSClientConfig: &tls.Config{12 },13 },14 }15 Transport(&http.Transport{16 TLSClientConfig: &tls.Config{17 },18 End()19 if errs != nil {20 log.Fatal(errs)21 }22 fmt.Println(body)23}24import (25func main() {26 caCert, err := ioutil.ReadFile("ca.pem")27 if err != nil {28 log.Fatal(err)29 }30 caCertPool := x509.NewCertPool()31 caCertPool.AppendCertsFromPEM(caCert)32 client := http.Client{33 Transport: &http.Transport{34 TLSClientConfig: &tls.Config{35 },36 },37 }38 Transport(&http.Transport{39 TLSClientConfig: &tls.Config{40 },41 End()42 if errs != nil {43 log.Fatal(errs)44 }45 fmt.Println(body)46}

Full Screen

Full Screen

GetTLSClientConfig

Using AI Code Generation

copy

Full Screen

1func main() {2 tlsConfig := httpmultibin.GetTLSClientConfig()3 tr := &http.Transport{4 }5 client := &http.Client{Transport: tr}6 if err != nil {7 log.Fatal(err)8 }9 defer resp.Body.Close()10 body, err := ioutil.ReadAll(resp.Body)11 if err != nil {12 log.Fatal(err)13 }14 fmt.Printf("%s15}16func main() {17 tlsConfig := httpmultibin.GetTLSClientConfig()18 tr := &http.Transport{19 }20 client := &http.Client{Transport: tr}21 if err != nil {22 log.Fatal(err)23 }24 defer resp.Body.Close()25 body, err := ioutil.ReadAll(resp.Body)26 if err != nil {27 log.Fatal(err)28 }29 fmt.Printf("%s30}31func main() {32 tlsConfig := httpmultibin.GetTLSClientConfig()33 tr := &http.Transport{34 }35 client := &http.Client{Transport: tr}36 if err != nil {37 log.Fatal(err)38 }39 defer resp.Body.Close()40 body, err := ioutil.ReadAll(resp.Body)41 if err != nil {42 log.Fatal(err)43 }

Full Screen

Full Screen

GetTLSClientConfig

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 httpClient := &http.Client{4 Transport: &http.Transport{5 TLSClientConfig: httpmultibin.GetTLSClientConfig(),6 },7 }8 if err != nil {9 log.Fatal(err)10 }11 defer resp.Body.Close()12 fmt.Println(resp.Status)13}14import (15func main() {16 httpClient := &http.Client{17 Transport: &http.Transport{18 TLSClientConfig: httpmultibin.GetTLSClientConfig(),19 },20 }21 if err != nil {22 log.Fatal(err)23 }24 defer resp.Body.Close()25 fmt.Println("Server certificate:")26 fmt.Println(" Subject:", serverCert.Subject)27 fmt.Println(" Issuer:", serverCert.Issuer)28 fmt.Println(" Serial Number:", serverCert.SerialNumber)29 fmt.Println(" Signature Algorithm:", serverCert.SignatureAlgorithm)30 fmt.Println(" Public Key Algorithm:", serverCert.PublicKeyAlgorithm)31 fmt.Println(" Public Key Size:", serverCert.PublicKey.(*rsa.PublicKey).Size()*8)32}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful