【问题标题】:HTTP2 not enabled by default on localhost默认情况下未在 localhost 上启用 HTTP2
【发布时间】:2017-12-05 14:10:27
【问题描述】:

我可能对此一无所知,但由于某种奇怪的原因,我的基本 localhost 服务器没有启用 HTTP2,我通常在 Caddy 后面代理,但由于我不想将我的域用于这个副项目,所以我创建了Go 中的一个基本服务器,然后运行它,它工作正常,但是标头显示 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

【问题讨论】:

    标签: http go localhost webserver http2


    【解决方案1】:

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

    Doc Reference:从Go 1.6开始,http包是透明的 使用 HTTPS 时支持 HTTP/2 协议。

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

    然后,通过

    访问它
    https://localhost:8081/
    

    【讨论】:

      猜你喜欢
      • 2014-12-17
      • 1970-01-01
      • 2018-04-11
      • 1970-01-01
      • 2014-05-28
      • 2012-02-29
      • 2018-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多