Go: 读取 http.Request 中的 Read 方法

huangapple go评论88阅读模式
英文:

Go: Read method in http.Request

问题

我正在阅读《Go Web Programming》一书,作者是Sau Sheong Chang。以下是一个从请求体中读取数据的示例代码:

import (
	"fmt"
	"net/http"
)

func bodyfunc(w http.ResponseWriter, r *http.Request) {
	len := r.ContentLength
	body := make([]byte, len)
	r.Body.Read(body)
	fmt.Fprintln(w, string(body))
}

func main() {
	server := http.Server{
		Addr: "127.0.0.1:8080",
	}
	http.HandleFunc("/body", bodyfunc)
	server.ListenAndServe()
}

根据定义,Request 结构体中的 Body 字段实际上是一个 io.ReadCloser 接口。我的问题是:该接口中的 Read 方法只是声明而没有实现。与此同时,代码可以正常工作。Read 方法的实现肯定是在某个地方完成的。它在哪里实现的呢?

英文:

I'm reading Go Web Programming by Sau Sheong Chang. Here is a sample code for reading data from a request body:

import (
	"fmt"
	"net/http"
)

func bodyfunc(w http.ResponseWriter, r *http.Request) {
	len := r.ContentLength
	body := make([]byte, len)
	r.Body.Read(body)
	fmt.Fprintln(w, string(body))
}

func main() {
	server := http.Server{
		Addr: "127.0.0.1:8080",
	}
	http.HandleFunc("/body", bodyfunc)
	server.ListenAndServe()
}

By definition, the Body field in the Request struct is actually an
io.ReadCloser interface. My question is: The Read method in this interface is just declared but not implemented. Meanwhile the code works well. The implementation of the Read method must have been done somewhere. Where is it?

答案1

得分: 0

这个实现在https://golang.org/src/net/http/transfer.go#L637中。我使用了delve调试器找到它。

英文:

The implementation is in https://golang.org/src/net/http/transfer.go#L637.
I used the delve debugger to find it.

huangapple
  • 本文由 发表于 2016年2月19日 16:42:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/35500854.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定