本地主机默认不启用 HTTP2

HTTP2 not enabled by default on localhost

我可能对此一无所知,但由于某些奇怪的原因,我的基本本地主机服务器没有启用 HTTP2,我通常在 Caddy 后面代理,但因为我不想将我的域用于这个副项目,我在 Go 中创建了一个基本服务器,运行 它工作正常,但是 headers 显示 HTTP/1.1 而不是 2.0,怎么了?

package main

import (
  "fmt"
  "net/http"
  "html/template"
  "os"
)

func IfError(err error, Quit bool) {
  if err != nil {
    fmt.Println(err.Error())
    if(Quit) {
      os.Exit(1);
    }
  }
}

func ServeHome(w http.ResponseWriter, r *http.Request) {
  t, err := template.ParseFiles("html/home")
  IfError(err, false)
  err = t.Execute(w, nil)
  IfError(err, false)
}

func RedirectRoot(fs http.Handler, home http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path == "/" {
      home.ServeHTTP(w, r)
    } else {
      fs.ServeHTTP(w, r)
    }
  })
}

func main()  {
  proto := ":8081"
  ServeFiles := http.FileServer(http.Dir("static/"))
  http.Handle("/", RedirectRoot(ServeFiles, http.HandlerFunc(ServeHome)))
  fmt.Printf("Listening on ... %s", proto)
  IfError(http.ListenAndServe(proto, nil), true)
}

非常基本的东西,但即使文档说它在默认情况下有效,它也不起作用。还有,我的go版本是1.8.3

是的,当您使用 SSL 证书时默认启用它。

Doc Reference: Starting with Go 1.6, the http package has transparent support for the HTTP/2 protocol when using HTTPS.

err := http.ListenAndServeTLS(":8081", "server.crt", "server.key", handler)
if err != nil && err != http.ErrServerClosed {
    log.Fatal("ListenAndServe: ", err)
}

然后,通过

访问它
https://localhost:8081/