1
0

modh2c.go 965 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package modh2c
  2. /*
  3. modh2c.go
  4. This module is a simple h2c roundtripper for dpcore
  5. */
  6. import (
  7. "context"
  8. "crypto/tls"
  9. "net"
  10. "net/http"
  11. "time"
  12. "golang.org/x/net/http2"
  13. )
  14. type H2CRoundTripper struct {
  15. }
  16. func NewH2CRoundTripper() *H2CRoundTripper {
  17. return &H2CRoundTripper{}
  18. }
  19. // Example from https://github.com/thrawn01/h2c-golang-example/blob/master/cmd/client/main.go
  20. func (h2c *H2CRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
  21. ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
  22. defer cancel()
  23. req, err := http.NewRequestWithContext(ctx, req.Method, req.RequestURI, nil)
  24. if err != nil {
  25. return nil, err
  26. }
  27. tr := &http2.Transport{
  28. AllowHTTP: true,
  29. DialTLSContext: func(ctx context.Context, network, addr string, cfg *tls.Config) (net.Conn, error) {
  30. var d net.Dialer
  31. return d.DialContext(ctx, network, addr)
  32. },
  33. }
  34. return tr.RoundTrip(req)
  35. }