英文:
Where is the Read method of http.Request.Body defined?
问题
首先,这是从日语翻译过来的,所以在措辞上可能会有一些错误。
我目前正在学习的书中列出了以下源代码。
package main
import (
"fmt"
"net/http"
)
func body(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", body)
server.ListenAndServe()
}
这部分调用了http.Request.Body
的Read
方法,这个问题是关于这部分的。
r.Body.Read(body)
为了实现io.ReadCloser
接口的Reader
方法,我认为我需要定义Read
方法,但是http
包的文档中没有提到Read
方法,请告诉我在哪里找到具体的实现。
英文:
First of all, this is a translation from Japanese, so there may be some mistakes in the wording.
The source code from the book that I am currently studying is listed below.
package main
import (
"fmt"
"net/http"
)
func body(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", body)
server.ListenAndServe()
}
This part calls the Read method of http.Request.Body, and this question is about this part.
r.Body.Read(body)
In order to implement the Reader interface of io.ReadCloser, I think I need to define the Read method, but the http package documentation does not mention the Read method, so please tell me where to find the specific implementation.
答案1
得分: 1
你可以看到
/net/http/transfer.go
func (b *body) Read(p []byte) (n int, err error) {
b.mu.Lock()
defer b.mu.Unlock()
if b.closed {
return 0, ErrBodyReadAfterClose
}
return b.readLocked(p)
}
如果没有body
/net/http/http.go
func (noBody) Read([]byte) (int, error) { return 0, io.EOF }
英文:
you can see
/net/http/transfer.go
func (b *body) Read(p []byte) (n int, err error) {
b.mu.Lock()
defer b.mu.Unlock()
if b.closed {
return 0, ErrBodyReadAfterClose
}
return b.readLocked(p)
}
if noBody
/net/http/http.go
func (noBody) Read([]byte) (int, error) { return 0, io.EOF }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论