knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/network/h2c.go (about) 1 /* 2 Copyright 2019 The Knative Authors 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package network 18 19 import ( 20 "context" 21 "crypto/tls" 22 "net" 23 "net/http" 24 "time" 25 26 "golang.org/x/net/http2" 27 "golang.org/x/net/http2/h2c" 28 ) 29 30 // NewServer returns a new HTTP Server with HTTP2 handler. 31 func NewServer(addr string, h http.Handler) *http.Server { 32 h1s := &http.Server{ 33 Addr: addr, 34 Handler: h2c.NewHandler(h, &http2.Server{}), 35 ReadHeaderTimeout: time.Minute, // https://medium.com/a-journey-with-go/go-understand-and-mitigate-slowloris-attack-711c1b1403f6 36 } 37 38 return h1s 39 } 40 41 // NewH2CTransport constructs a new H2C transport. 42 // That transport will reroute all HTTPS traffic to HTTP. This is 43 // to explicitly allow h2c (http2 without TLS) transport. 44 // See https://github.com/golang/go/issues/14141 for more details. 45 func NewH2CTransport() http.RoundTripper { 46 return newH2CTransport(false) 47 } 48 49 func newH2CTransport(disableCompression bool) http.RoundTripper { 50 return &http2.Transport{ 51 AllowHTTP: true, 52 DisableCompression: disableCompression, 53 DialTLS: func(netw, addr string, _ *tls.Config) (net.Conn, error) { 54 return DialWithBackOff(context.Background(), 55 netw, addr) 56 }, 57 } 58 } 59 60 // newH2Transport constructs a neew H2 transport. That transport will handles HTTPS traffic 61 // with TLS config. 62 func newH2Transport(disableCompression bool, tlsContext DialTLSContextFunc) http.RoundTripper { 63 return &http2.Transport{ 64 DisableCompression: disableCompression, 65 DialTLSContext: func(ctx context.Context, network, addr string, cfg *tls.Config) (net.Conn, error) { 66 return tlsContext(ctx, network, addr) 67 }, 68 } 69 }