http.Request.Body的Read方法定义在哪里?

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

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.BodyRead方法,这个问题是关于这部分的。

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 }

huangapple
  • 本文由 发表于 2021年7月6日 13:25:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/68264992.html
匿名

发表评论

匿名网友

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

确定