Skip to content

Instantly share code, notes, and snippets.

@thrawn01
Last active April 19, 2024 20:32
Show Gist options
  • Select an option

  • Save thrawn01/532dd854d9b48c102f3ddf35ec93bff1 to your computer and use it in GitHub Desktop.

Select an option

Save thrawn01/532dd854d9b48c102f3ddf35ec93bff1 to your computer and use it in GitHub Desktop.
How to add h2c support to existing HTTP/2 HTTP/1 servers
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")
@hzpfly

hzpfly commented Aug 29, 2019

Copy link
Copy Markdown

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".

@thrawn01

Copy link
Copy Markdown
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