我正在研究 的http 源代码Golang,我发现了这个
func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error) {
...
rc, ok := body.(io.ReadCloser)
...
}
Run Code Online (Sandbox Code Playgroud)
但这body是nil,它是通过以下方式传递的
func NewRequest(method, url string, body io.Reader) (*Request, error) {
return NewRequestWithContext(context.Background(), method, url, body)
}
func (c *Client) Get(url string) (resp *Response, err error) {
req, err := NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
return c.Do(req)
}
Run Code Online (Sandbox Code Playgroud)
函数Get传递nil给函数NewRequest,
函数NewRequest将 this 传递nil给 function NewRequestWithContext,
那么函数 NewRequestWithContext使用nil来调用nil.(io.ReadCloser),为什么不导致呢panic?
该声明
rc, ok := body.(io.ReadCloser)
Run Code Online (Sandbox Code Playgroud)
测试是否body是 a ReadCloser。如果不是,则将rc被设置为nil,并且ok将被设置为false。
如果代码是:
rc:=body.(io.ReadCloser)
Run Code Online (Sandbox Code Playgroud)
那么如果身体为零,它就会恐慌。