在學(xué)習(xí)期間,我實(shí)際上想知道如何回到聽眾身邊。從這個(gè)答案中,我發(fā)現(xiàn)了http。響應(yīng)類型被傳遞給ServeHTTP,但事實(shí)并非如此,因?yàn)樵诰幾g時(shí)下面的代碼拋出錯(cuò)誤。這意味著不實(shí)現(xiàn)接口。我很好奇實(shí)現(xiàn)接口的類型是什么?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貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
網(wǎng)易娛樂.響應(yīng)僅具有以下方法:
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
這不會(huì)實(shí)現(xiàn) http。響應(yīng)編寫器接口,需要:
Header() Header
Write([]byte) (int, error)
WriteHeader(statusCode int)
所以顯然不能用作.http.Responsehttp.ResponseWriter
相反,正如您鏈接到的答案所提到的,將使用未導(dǎo)出的 http.響應(yīng)。您可以在代碼中找到對(duì) http 服務(wù)器端寫入的生存期的描述。
- 1 回答
- 0 關(guān)注
- 86 瀏覽
添加回答
舉報(bào)
0/150
提交
取消