繁体   English   中英

Go net/http package 中的 ResponseWriter 接口

[英]ResponseWriter interface in Go net/http package

我有两个关于 net/http package 中的 ResponseWriter 接口的问题。 这是我的代码

package main

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

type handler struct{}

func (h *handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    fmt.Fprintf(w, "Method: %v\n", req.Method)
    fmt.Fprintf(w, "URL: %v\n", req.URL)
    fmt.Fprintf(w, "Protocol: %v\n", req.Proto)

    fmt.Fprintf(os.Stdout, "Header: %v\n", w.Header())
}

func main() {
    http.ListenAndServe(":8080", &handler{})
}

并检查我在 cmd 中使用的代码 curl。 您可以在下面看到 curl 命令及其结果。

C:\Users>curl -i -X GET localhost:8080
HTTP/1.1 200 OK
Date: Fri, 19 Aug 2022 03:47:21 GMT
Content-Length: 38
Content-Type: text/plain; charset=utf-8

Method: GET
URL: /
Protocol: HTTP/1.1

由于 http.ResponseWriter 只是一个接口,我没有在我的程序中实现任何具体类型来满足这个接口,为什么我的代码可以工作? 据我了解,没有接口方法的实现。 那么如何从 curl 得到正确的响应呢?

此外,正如您在 curl 的 output 中看到的那样,我收到了 http 响应,其中包含 Z099E6221F6393D9FAA8F8Z 响应。 但是, fmt.Fprintf(os.Stdout, "Header: %v\n", w.Header())的 output 是Header: map[] If I am right, Header method for http.ResponseWriter must return the response header which is not empty based on the curl output. 那么为什么 Fprintf 返回一个空的Fprintf呢?

谢谢您的帮助。

由于 http.ResponseWriter 只是一个接口,我没有在我的程序中实现任何具体类型来满足这个接口,为什么我的代码可以工作?

没有; 标准库有(即私有http.responsehttp.http2responsewriter类型)。 http 服务器将其中一种类型的实例传递给您的处理程序。 你不需要知道它是什么; 你只知道无论你得到什么,它都会实现ResponseWriter方法。

那么为什么 Fprintf 返回一个空的 map 呢?

因为 map 是空的,因为您没有设置任何标题。 如果您不自己设置某些服务器(如DateContent-Type ),则服务器可以自动设置它们,但这是在您打印之后发生的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM