request 表示由服务器接收或由客户端发送的HTTP请求,例如客户端(client)在发送各种请求时,需要先新建一个请求对象,然后调用一些请求的方法开始自定义一些配置,服务端监听到该请求便会做出相应的应答
源码解析
request错误类型
const (
defaultMaxMemory = 32 << 20
)
var ErrMissingFile = errors.New("http: no such file")
type ProtocolError struct {
ErrorString string
}
func (pe *ProtocolError) Error() string { return pe.ErrorString }
var (
ErrNotSupported = &ProtocolError{"feature not supported"}
ErrMissingBoundary = &ProtocolError{"no multipart boundary param in Content-Type"}
ErrNotMultipart = &ProtocolError{"request Content-Type isn't multipart/form-data"}
)
func badStringError(what, val string) error { return fmt.Errorf("%s %q", what, val) }
- ErrMissingFile:这是请求对象的一个查找方法返回的错误,调用了errors包的New方法来返回一个错误类型的错误(即errors.New可以传string类型参数 来返回一个简单的字符串错误)
- ProtocolError :ProtocolError表示HTTP协议错误结构体对象。该对象 实现了error接口(Error() string),因此,所有该结构体实例都可以当成error返回传参
- badStringError:是一个根据两个 string参数返回一个error的函数,当必要时,可以调用此函数实现返回错误
request 结构体定义
var reqWriteExcludeHeader = map[string]bool{
"Host": true,
"User-Agent": true,
"Content-Length": true,
"Transfer-Encoding": true,
"Trailer": true,
}
type Request struct {
Method string
URL *url.URL
Proto string
ProtoMajor int
ProtoMinor int
Header Header
Body io.ReadCloser
GetBody func() (io.ReadCloser, error)
ContentLength int64
TransferEncoding []string
Close bool
Host string
Form url.Values
PostForm url.Values
MultipartForm *multipart.Form
Trailer Header
RemoteAddr string
RequestURI string
TLS *tls.ConnectionState
Cancel <-chan struct{}
Response *Response
ctx context.Context
}
在上面的代码中,我们定义了 http.Request类型中的公开数据成员,备注详细说明了其中的各行代码。
下面介绍 该对象的 获取内部成员ctx(上下文)的方法,2个修改上下文方法(都用到了内部自定义clone函数)
func (r *Request) Context() context.Context {
if r.ctx != nil {
return r.ctx
}
return context.Background()
}
func (r *Request) WithContext(ctx context.Context) *Request {
if ctx == nil {
panic("nil context")
}
r2 := new(Request)
*r2 = *r
r2.ctx = ctx
r2.URL = cloneURL(r.URL)
return r2
}
func (r *Request) Clone(ctx context.Context) *Request {
if ctx == nil {
panic("nil context")
}
r2 := new(Request)
*r2 = *r
r2.ctx = ctx
r2.URL = cloneURL(r.URL)
if r.Header != nil {
r2.Header = r.Header.Clone()
}
if r.Trailer != nil {
r2.Trailer = r.Trailer.Clone()
}
if s := r.TransferEncoding; s != nil {
s2 := make([]string, len(s))
copy(s2, s)
r2.TransferEncoding = s2
}
r2.Form = cloneURLValues(r.Form)
r2.PostForm = cloneURLValues(r.PostForm)
r2.MultipartForm = cloneMultipartForm(r.MultipartForm)
return r2
}
func (r *Request) ProtoAtLeast(major, minor int) bool {
return r.ProtoMajor > major ||
r.ProtoMajor == major && r.ProtoMinor >= minor
}
- Context():获取对象内部成员,可以使用一个公开的方法封装实现
- WithContext(): 更改请求的上下文方法一,传入新的上下文,返回修改后的请求–r的浅层副本,该方法 通过新建一个变量,使变量的指针指向原 请求,然后克隆请求的URL实现。此方法很少用。要使用上下文创建新请求,请使用NewRequestWithContext
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)