跳转到内容

HTTP/2 服务器

HTTP/2 通过请求复用和 header 压缩改善延迟。Go 的 HTTP 服务器会在 TLS 上自动协商 HTTP/2,因此使用 Echo 提供 HTTP/2 只需用证书启动服务器。

运行以下命令生成 cert.pem 和 key.pem:

终端窗口
go run $GOROOT/src/crypto/tls/generate_cert.go --host localhost

2. 创建回显请求信息的处理函数

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

使用生成的证书和 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.0
Host: localhost:1323
Remote Address: [::1]:60288
Method: GET
Path: /
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)
}
}