How can I set up a http2 server in Go 1.8 without third party libraries?

huangapple go评论100阅读模式
英文:

How can I set up a http2 server in Go 1.8 without third party libraries?

问题

我听说最新的Go版本将支持http2。如何在不使用golang.org/x/net/http2的情况下搭建一个http2服务器?

在之前的版本中,你可以这样做:

  1. package main
  2. import (
  3. "log"
  4. "net/http"
  5. "os"
  6. "golang.org/x/net/http2"
  7. )
  8. func main() {
  9. cwd, err := os.Getwd()
  10. if err != nil {
  11. log.Fatal(err)
  12. }
  13. srv := &http.Server{
  14. Addr: ":443",
  15. Handler: http.FileServer(http.Dir(cwd)),
  16. }
  17. http2.ConfigureServer(srv, &http2.Server{})
  18. log.Fatal(srv.ListenAndServeTLS("server.crt", "server.key"))
  19. }

希望对你有帮助!

英文:

I heard that http2 would be supported in the latest Go versions. How can I put up a http2 server without using golang.org/x/net/http2?

In previous versions you could do something like this:

  1. package main
  2. import (
  3. "log"
  4. "net/http"
  5. "os"
  6. "golang.org/x/net/http2"
  7. )
  8. func main() {
  9. cwd, err := os.Getwd()
  10. if err != nil {
  11. log.Fatal(err)
  12. }
  13. srv := &http.Server{
  14. Addr: ":443",
  15. Handler: http.FileServer(http.Dir(cwd)),
  16. }
  17. http2.ConfigureServer(srv, &http2.Server{})
  18. log.Fatal(srv.ListenAndServeTLS("server.crt", "server.key"))
  19. }

答案1

得分: 3

在大多数情况下,你只需要使用net/http

> 从Go 1.6开始,当使用HTTPS时,http包对HTTP/2协议具有透明的支持。
>
> http包的Transport和Server在简单配置下会自动启用HTTP/2支持。要在更复杂的配置中启用HTTP/2,使用更低级别的HTTP/2功能,或者使用Go的http2包的新版本,请直接导入golang.org/x/net/http2并使用其ConfigureTransport和/或ConfigureServer函数。通过golang.org/x/net/http2包手动配置HTTP/2优先于net/http包内置的HTTP/2支持。

英文:

You just use net/http in most instances:

> Starting with Go 1.6, the http package has transparent support for the HTTP/2 protocol when using HTTPS.
>
> The http package's Transport and Server both automatically enable HTTP/2 support for simple configurations. To enable HTTP/2 for more complex configurations, to use lower-level HTTP/2 features, or to use a newer version of Go's http2 package, import "golang.org/x/net/http2" directly and use its ConfigureTransport and/or ConfigureServer functions. Manually configuring HTTP/2 via the golang.org/x/net/http2 package takes precedence over the net/http package's built-in HTTP/2 support.

huangapple
  • 本文由 发表于 2017年3月15日 07:28:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/42798419.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定