我创建了一个简单的http2服务器, 如果我使用curl向它发送请求,它会以一些标头响应,尽管我没有明确设置它们。如何在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-不安全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
我看到一些标头被发回,我明确设置的标头也收到了,但是
的输出运行server.go
[RESPONSE][Header] Myfirst : [golangQuestion]
我如何访问其他未明确设置但也可以通过curl接收的标头?我遍历了 w.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]
答案 0 :(得分:1)
当您致电ResponseWriter.Write()
时,这些标题会自动发送。引用其文档:
// 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()
仅包含显式设置的标头。 Content-Type
和Content-Length
由w.Write()
发送。
注意:如果要禁止显示此类自动标头,则必须将其值设置为nil
,例如:
w.Header()["Date"] = nil
还请注意,如果您手动设置此类标头的值,这些值将被发送而不会被更改。