http2-server

HTTP/2 Server

原文:https://echo.labstack.com/docs/cookbook/http2

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

NOTE

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

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

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

or use customized HTTP server with your own TLSConfig

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

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

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

Source Code

cookbook/http2/server.go

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main

import (
	"fmt"
	"net/http"

	"github.com/labstack/echo/v4"
)

func main() {
	e := echo.New()
	e.GET("/request", func(c echo.Context) error {
		req := c.Request()
		format := `
			<code>
				Protocol: %s<br>
				Host: %s<br>
				Remote Address: %s<br>
				Method: %s<br>
				Path: %s<br>
			</code>
		`
		return c.HTML(http.StatusOK, fmt.Sprintf(format, req.Proto, req.Host, req.RemoteAddr, req.Method, req.URL.Path))
	})
	e.Logger.Fatal(e.StartTLS(":1323", "cert.pem", "key.pem"))
}
最后修改 October 10, 2024: 更新 (a4b8f85)