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. リクエスト情報を echo するハンドラを作成する
Section titled “2. リクエスト情報を echo するハンドラを作成する”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-server4. 検証する
Section titled “4. 検証する”サーバーを起動して https://localhost:1323/request にアクセスします。次のような出力が表示されます。
Protocol: HTTP/2.0Host: localhost:1323Remote Address: [::1]:60288Method: GETPath: /ソースコード
Section titled “ソースコード”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) }}