我创建了一个简单的http2服务器, 如果我使用curl向它发送请求,它会以一些header响应,尽管我没有明确设置它们。如何在requesthandling函数(sayhello)中访问它们?我的代码(我以前从未使用过golang)

server.go

package main

import (
  "net/http"
  "strings"
  "fmt"
  "github.com/gorilla/mux"
  "golang.org/x/net/http2"
)

func sayHello(w http.ResponseWriter, r *http.Request) {
  message := r.URL.Path
  message = strings.TrimPrefix(message, "/")
  message = "Hello " + message

  w.Header().Set("myFirst", "golangQuestion")
  w.Write([]byte(message))
  for k, v := range w.Header() {
    fmt.Println("[RESPONSE][Header]", k,":", v)
    }
}

func main() {
    router := mux.NewRouter()
    router.PathPrefix("/").HandlerFunc(sayHello) // catch everything else rule
    var srv = &http.Server{
        Addr: "127.0.0.1:8081",
    }
    http2.ConfigureServer(srv, nil)
    srv.Handler = router
    sslCert := "./ssl.cert"
    sslKey := "./ssl.key"
    if err := srv.ListenAndServeTLS(sslCert, sslKey); err != nil {
        panic(err)
    }
}

发送请求:

curl --head --insecure https://127.0.0.1:8081

HTTP/1.1 200 OK
Myfirst: golangQuestion
Date: Tue, 18 Jun 2019 09:18:29 GMT
Content-Length: 6
Content-Type: text/plain; charset=utf-8

我可以看到一些header被发回,我明确设置的header也收到了,但是输出

go run server.go

[RESPONSE][Header] Myfirst : [golangQuestion]

如何访问其他未明确设置但也由curl接收的header?我查看了with.Headers,但是它不包含隐式设置的标题

  for k, v := range w.Header() {
    fmt.Println("[RESPONSE][Header]", k,":", v)
    }

我期望go run server.go的输出应如下所示:

[RESPONSE][Header] Myfirst : [golangQuestion]
[RESPONSE][Header] Date: [2019.02.12 ]
[RESPONSE][Header] Content-Length: [6]
分析解答

调用ResponseWriter.Write()时,将自动发送这些header。引用其文档:

// Write writes the data to the connection as part of an HTTP reply.
//
// If WriteHeader has not yet been called, Write calls
// WriteHeader(http.StatusOK) before writing the data. If the Header
// does not contain a Content-Type line, Write adds a Content-Type set
// to the result of passing the initial 512 bytes of written data to
// DetectContentType. Additionally, if the total size of all written
// data is under a few KB and there are no Flush calls, the
// Content-Length header is added automatically.
//
// Depending on the HTTP protocol version and the client, calling
// Write or WriteHeader may prevent future reads on the
// Request.Body. For HTTP/1.x requests, handlers should read any
// needed request body data before writing the response. Once the
// headers have been flushed (due to either an explicit Flusher.Flush
// call or writing enough data to trigger a flush), the request body
// may be unavailable. For HTTP/2 requests, the Go HTTP server permits
// handlers to continue to read the request body while concurrently
// writing the response. However, such behavior may not be supported
// by all HTTP/2 clients. Handlers should read before writing if
// possible to maximize compatibility.
Write([]byte) (int, error)

ResponseWriter.Header()仅包含显式设置的header。 Content-TypeContent-Lengthw.Write()发送。

注意:如果要禁止显示此类自动header,则必须将其值设置为nil,例如:

w.Header()["Date"] = nil

另请注意,如果您手动设置此类header的值,这些值将被发送而不会被更改。