Last active
April 19, 2024 20:32
-
-
Save thrawn01/532dd854d9b48c102f3ddf35ec93bff1 to your computer and use it in GitHub Desktop.
How to add h2c support to existing HTTP/2 HTTP/1 servers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| h2s := &http2.Server{} | |
| handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| fmt.Fprintf(w, "Hello, %v, http: %v", r.URL.Path, r.TLS == nil) | |
| }) | |
| server := &http.Server{ | |
| Addr: "0.0.0.0:1010", | |
| Handler: h2c.NewHandler(handler, h2s), | |
| } | |
| // Call ConfigureServer() to register graceful shutdown handlers which allows | |
| // the server to terminate client streams when calling server.Shutdown() | |
| checkErr(http2.ConfigureServer(server, h2s), "during ConfigureServer") | |
| fmt.Printf("Listening [0.0.0.0:1010]...\n") | |
| checkErr(server.ListenAndServe(), "while listening") |
Author
it works just like standard golang http handler does. See https://golang.org/pkg/net/http/#example_ServeMux_Handle for an example of using the mux to add handlers.
I made a complete example project demonstrating h2c in golang (client and server) https://github.com/thrawn01/h2c-golang-example
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for the wonderful example of h2c.
Can I ask one question: how to add more handler function? For example, one handler for "/", another handler for "/answer".