我正在阅读 Sau Sheong Chang 的Go Web Programming。以下是从请求正文中读取数据的示例代码:
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
接口(interface)。我的问题是:这个接口(interface)中的Read
方法只是声明了没有实现。同时代码运行良好。 Read
方法的实现一定是在某个地方完成的。它在哪里?
最佳答案
实现在 https://golang.org/src/net/http/transfer.go#L637 中. 我用了delve调试器找到它。
关于Go: 读取 http.Request 中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35500854/