英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论