github.com/apernet/quic-go@v0.43.1-0.20240515053213-5e9e635fd9f0/example/client/main.go (about)

     1  package main
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/tls"
     6  	"crypto/x509"
     7  	"flag"
     8  	"io"
     9  	"log"
    10  	"net/http"
    11  	"os"
    12  	"sync"
    13  
    14  	"github.com/apernet/quic-go"
    15  	"github.com/apernet/quic-go/http3"
    16  	"github.com/apernet/quic-go/internal/testdata"
    17  	"github.com/apernet/quic-go/qlog"
    18  )
    19  
    20  func main() {
    21  	quiet := flag.Bool("q", false, "don't print the data")
    22  	keyLogFile := flag.String("keylog", "", "key log file")
    23  	insecure := flag.Bool("insecure", false, "skip certificate verification")
    24  	flag.Parse()
    25  	urls := flag.Args()
    26  
    27  	var keyLog io.Writer
    28  	if len(*keyLogFile) > 0 {
    29  		f, err := os.Create(*keyLogFile)
    30  		if err != nil {
    31  			log.Fatal(err)
    32  		}
    33  		defer f.Close()
    34  		keyLog = f
    35  	}
    36  
    37  	pool, err := x509.SystemCertPool()
    38  	if err != nil {
    39  		log.Fatal(err)
    40  	}
    41  	testdata.AddRootCA(pool)
    42  
    43  	roundTripper := &http3.RoundTripper{
    44  		TLSClientConfig: &tls.Config{
    45  			RootCAs:            pool,
    46  			InsecureSkipVerify: *insecure,
    47  			KeyLogWriter:       keyLog,
    48  		},
    49  		QUICConfig: &quic.Config{
    50  			Tracer: qlog.DefaultTracer,
    51  		},
    52  	}
    53  	defer roundTripper.Close()
    54  	hclient := &http.Client{
    55  		Transport: roundTripper,
    56  	}
    57  
    58  	var wg sync.WaitGroup
    59  	wg.Add(len(urls))
    60  	for _, addr := range urls {
    61  		log.Printf("GET %s", addr)
    62  		go func(addr string) {
    63  			rsp, err := hclient.Get(addr)
    64  			if err != nil {
    65  				log.Fatal(err)
    66  			}
    67  			log.Printf("Got response for %s: %#v", addr, rsp)
    68  
    69  			body := &bytes.Buffer{}
    70  			_, err = io.Copy(body, rsp.Body)
    71  			if err != nil {
    72  				log.Fatal(err)
    73  			}
    74  			if *quiet {
    75  				log.Printf("Response Body: %d bytes", body.Len())
    76  			} else {
    77  				log.Printf("Response Body (%d bytes):\n%s", body.Len(), body.Bytes())
    78  			}
    79  			wg.Done()
    80  		}(addr)
    81  	}
    82  	wg.Wait()
    83  }