Search code examples
httpgolocalhostwebserverhttp2

HTTP2 not enabled by default on localhost


I might be just clueless on this but my basic localhost server doesn't have HTTP2 Enabled for some odd reason, I normally proxy behind Caddy, but as I don't want to use my domain for this side project, I created a basic server in Go, and ran it, it works okay, but the headers show HTTP/1.1 instead of 2.0, what's wrong?

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)
}

Very basic stuff, but doesn't work even thought the documentation says it works by default. Also, my go version is 1.8.3


Solution

  • Yes, its enabled by default when you use with SSL certs.

    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)
    }
    

    Then, access it via

    https://localhost:8081/