在學習期間,我實際上想知道如何回到聽眾身邊。從這個答案中,我發現了http。響應類型被傳遞給ServeHTTP,但事實并非如此,因為在編譯時下面的代碼拋出錯誤。這意味著不實現接口。我很好奇實現接口的類型是什么?net/httphttp.Responsehttp.Responsehttp.ResponseWriterhttp.ResponseWriter# command-line-arguments./server1.go:9:20: http.Response.Header is a field, not a method./server1.go:9:20: impossible type assertion: http.Response does not implement http.ResponseWriter (missing Header method)func handler(resp http.ResponseWriter, req *http.Request){ actualresp := resp.(http.Response) //https://tour.golang.org/methods/15 resp.Write([]byte("Hello Web, from go"))}func main(){ http.HandleFunc("/api", handler) http.ListenAndServe(":8000", nil)}
1 回答

慕絲7291255
TA貢獻1859條經驗 獲得超6個贊
網易娛樂.響應僅具有以下方法:
func (r *Response) Cookies() []*Cookie
func (r *Response) Location() (*url.URL, error)
func (r *Response) ProtoAtLeast(major, minor int) bool
func (r *Response) Write(w io.Writer) error
這不會實現 http。響應編寫器接口,需要:
Header() Header
Write([]byte) (int, error)
WriteHeader(statusCode int)
所以顯然不能用作.http.Responsehttp.ResponseWriter
相反,正如您鏈接到的答案所提到的,將使用未導出的 http.響應。您可以在代碼中找到對 http 服務器端寫入的生存期的描述。
- 1 回答
- 0 關注
- 89 瀏覽
添加回答
舉報
0/150
提交
取消