HTTP/2 服务器
HTTP/2 通过请求复用和 header 压缩改善延迟。Go 的 HTTP 服务器会在 TLS 上自动协商 HTTP/2,因此使用 Echo 提供 HTTP/2 只需用证书启动服务器。
1. 生成自签名 X.509 TLS 证书
Section titled “1. 生成自签名 X.509 TLS 证书”运行以下命令生成 cert.pem 和 key.pem:
go run $GOROOT/src/crypto/tls/generate_cert.go --host localhost2. 创建回显请求信息的处理函数
Section titled “2. 创建回显请求信息的处理函数”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. 启动 TLS 服务器
Section titled “3. 启动 TLS 服务器”使用生成的证书和 key 启动服务器:
sc := echo.StartConfig{Address: ":1323"}if err := sc.StartTLS(context.Background(), e, "cert.pem", "key.pem"); err != nil { e.Logger.Error("failed to start server", "error", err)}或者使用带自定义 tls.Config 的自定义 http.Server:
s := http.Server{ Addr: ":1323", Handler: e, TLSConfig: &tls.Config{ MinVersion: tls.VersionTLS12, }, // ReadTimeout: 30 * time.Second, // use custom timeouts}if err := s.ListenAndServeTLS("cert.pem", "key.pem"); err != nil && !errors.Is(err, http.ErrServerClosed) { e.Logger.Error("failed to start server", "error", err)}go run . -custom-server启动服务器并访问 https://localhost:1323/request。你应该会看到类似下面的输出:
Protocol: HTTP/2.0Host: localhost:1323Remote Address: [::1]:60288Method: GETPath: /package main
import ( "context" "crypto/tls" "errors" "flag" "fmt" "net/http"
"github.com/labstack/echo/v5")
func main() { customServer := flag.Bool("custom-server", false, "use a standard http.Server") flag.Parse() 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)) }) if *customServer { customHTTPServer(e) return } sc := echo.StartConfig{Address: ":1323"} if err := sc.StartTLS(context.Background(), e, "cert.pem", "key.pem"); err != nil { e.Logger.Error("failed to start server", "error", err) }}
// customHTTPServer demonstrates configuring TLS with a standard HTTP server.func customHTTPServer(e *echo.Echo) { s := http.Server{ Addr: ":1323", Handler: e, TLSConfig: &tls.Config{ MinVersion: tls.VersionTLS12, }, // ReadTimeout: 30 * time.Second, // use custom timeouts } if err := s.ListenAndServeTLS("cert.pem", "key.pem"); err != nil && !errors.Is(err, http.ErrServerClosed) { e.Logger.Error("failed to start server", "error", err) }}