HTTP/2

How to run an HTTP/2 server?

Step 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

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

Step 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. })

Step 3: Configure TLS server using cert.pem and key.pem

  1. e.StartTLS(":1323", "cert.pem", "key.pem")

Step 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

server.go

  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "github.com/labstack/echo"
  6. )
  7. func main() {
  8. e := echo.New()
  9. e.GET("/request", func(c echo.Context) error {
  10. req := c.Request()
  11. format := `
  12. <code>
  13. Protocol: %s<br>
  14. Host: %s<br>
  15. Remote Address: %s<br>
  16. Method: %s<br>
  17. Path: %s<br>
  18. </code>
  19. `
  20. return c.HTML(http.StatusOK, fmt.Sprintf(format, req.Proto, req.Host, req.RemoteAddr, req.Method, req.URL.Path))
  21. })
  22. e.Logger.Fatal(e.StartTLS(":1323", "cert.pem", "key.pem"))
  23. }

Maintainers