Senior
How does Go support HTTP/2?
sobes.tech AI
Answer from AI
Go supports HTTP/2 at the standard library level net/http without the need for additional configuration. The built-in HTTP server automatically uses HTTP/2 when the connection is over TLS and the client supports this protocol. This provides improved performance through request multiplexing and header compression.
Example of a simple HTTP server with HTTP/2 support:
package main
import (
"log"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, HTTP/2!"))
}
func main() {
http.HandleFunc("/", handler)
// Running the server with TLS, which automatically enables HTTP/2
log.Fatal(http.ListenAndServeTLS(":8443", "server.crt", "server.key", nil))
}
HTTP/2 support for clients is automatic in http.Client when using TLS. For more fine-tuned configuration, you can use the package golang.org/x/net/http2.