HTTP/2 Server

1) Generate a self-signed X.509 TLS certificate

Run the following command to generate cert.pem and key.pem files:

  1. go run $GOROOT/src/crypto/tls/generate_cert.go --host localhost

HTTP/2 Server - 图1note

For demo purpose, we are using a self-signed certificate. Ideally, you should obtain a certificate from CA.

2) Create a handler which simply outputs the request information to the client

  1. e.GET("/request", func(c echo.Context) error {
  2. req := c.Request()
  3. format := `
  4. <code>
  5. Protocol: %s<br>
  6. Host: %s<br>
  7. Remote Address: %s<br>
  8. Method: %s<br>
  9. Path: %s<br>
  10. </code>
  11. `
  12. return c.HTML(http.StatusOK, fmt.Sprintf(format, req.Proto, req.Host, req.RemoteAddr, req.Method, req.URL.Path))
  13. })

3) Start TLS server using cert.pem and key.pem

  1. if err := e.StartTLS(":1323", "cert.pem", "key.pem"); err != http.ErrServerClosed {
  2. log.Fatal(err)
  3. }

or use customized HTTP server with your own TLSConfig

  1. s := http.Server{
  2. Addr: ":8443",
  3. Handler: e, // set Echo as handler
  4. TLSConfig: &tls.Config{
  5. //Certificates: nil, // <-- s.ListenAndServeTLS will populate this field
  6. },
  7. //ReadTimeout: 30 * time.Second, // use custom timeouts
  8. }
  9. if err := s.ListenAndServeTLS("cert.pem", "key.pem"); err != http.ErrServerClosed {
  10. log.Fatal(err)
  11. }

4) Start the server and browse to https://localhost:1323/request to see the following output

  1. Protocol: HTTP/2.0
  2. Host: localhost:1323
  3. Remote Address: [::1]:60288
  4. Method: GET
  5. Path: /

Source Code

cookbook/http2/server.go

  1. loading...