英文:
How can I set up a http2 server in Go 1.8 without third party libraries?
问题
我听说最新的Go版本将支持http2。如何在不使用golang.org/x/net/http2
的情况下搭建一个http2服务器?
在之前的版本中,你可以这样做:
package main
import (
"log"
"net/http"
"os"
"golang.org/x/net/http2"
)
func main() {
cwd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
srv := &http.Server{
Addr: ":443",
Handler: http.FileServer(http.Dir(cwd)),
}
http2.ConfigureServer(srv, &http2.Server{})
log.Fatal(srv.ListenAndServeTLS("server.crt", "server.key"))
}
希望对你有帮助!
英文:
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:
package main
import (
"log"
"net/http"
"os"
"golang.org/x/net/http2"
)
func main() {
cwd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
srv := &http.Server{
Addr: ":443",
Handler: http.FileServer(http.Dir(cwd)),
}
http2.ConfigureServer(srv, &http2.Server{})
log.Fatal(srv.ListenAndServeTLS("server.crt", "server.key"))
}
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论