fasthttp 文檔手冊
貌似文章有最大長度限制,完整全文地址:https://github.com/DavidCai1993/my-blog/issues/35html
常量
const (
CompressNoCompression = flate.NoCompression
CompressBestSpeed = flate.BestSpeed
CompressBestCompression = flate.BestCompression
CompressDefaultCompression = flate.DefaultCompression
)
所支持的壓縮級別。git
const (
StatusContinue = 100
StatusSwitchingProtocols = 101
StatusProcessing = 102
StatusOK = 200
StatusCreated = 201
StatusAccepted = 202
StatusNonAuthoritativeInfo = 203
StatusNoContent = 204
StatusResetContent = 205
StatusPartialContent = 206
StatusMultiStatus = 207
StatusAlreadyReported = 208
StatusIMUsed = 226
StatusMultipleChoices = 300
StatusMovedPermanently = 301
StatusFound = 302
StatusSeeOther = 303
StatusNotModified = 304
StatusUseProxy = 305
StatusTemporaryRedirect = 307
StatusPermanentRedirect = 308
StatusBadRequest = 400
StatusUnauthorized = 401
StatusPaymentRequired = 402
StatusForbidden = 403
StatusNotFound = 404
StatusMethodNotAllowed = 405
StatusNotAcceptable = 406
StatusProxyAuthRequired = 407
StatusRequestTimeout = 408
StatusConflict = 409
StatusGone = 410
StatusLengthRequired = 411
StatusPreconditionFailed = 412
StatusRequestEntityTooLarge = 413
StatusRequestURITooLong = 414
StatusUnsupportedMediaType = 415
StatusRequestedRangeNotSatisfiable = 416
StatusExpectationFailed = 417
StatusTeapot = 418
StatusUnprocessableEntity = 422
StatusLocked = 423
StatusFailedDependency = 424
StatusUpgradeRequired = 426
StatusPreconditionRequired = 428
StatusTooManyRequests = 429
StatusRequestHeaderFieldsTooLarge = 431
StatusUnavailableForLegalReasons = 451
StatusInternalServerError = 500
StatusNotImplemented = 501
StatusBadGateway = 502
StatusServiceUnavailable = 503
StatusGatewayTimeout = 504
StatusHTTPVersionNotSupported = 505
StatusVariantAlsoNegotiates = 506
StatusInsufficientStorage = 507
StatusLoopDetected = 508
StatusNotExtended = 510
StatusNetworkAuthenticationRequired = 511
)
與 net/http 相同的 HTTP 狀態嗎。github
const DefaultConcurrency = 256 * 1024
DefaultConcurrency
爲默認狀況下(沒有設置 Server.Concurrency
時)服務器能夠接受的最大併發請求數。瀏覽器
const DefaultDNSCacheDuration = time.Minute
DefaultDNSCacheDuration
是由 Dial*
函數族緩存處理過的 TCP 地址的持續時間。緩存
const DefaultDialTimeout = 3 * time.Second
DefaultDialTimeout
是由 Dial
和 DialDualStack
使用的用於創建 TCP 鏈接的超時時間。安全
const DefaultMaxConnsPerHost = 512
DefaultMaxConnsPerHost
是 http 客戶端在默認狀況下(若是沒有設置 Client.MaxConnsPerHost
)單個 host 能夠創建的最大併發鏈接數。服務器
const DefaultMaxIdleConnDuration = 10 * time.Second
DefaultMaxIdleConnDuration
是在空閒的 keep-alive 鏈接被關閉前默認的持續時間。cookie
const DefaultMaxPendingRequests = 1024
DefaultMaxPendingRequests
是 PipelineClient.MaxPendingRequests
的默認值。網絡
const DefaultMaxRequestBodySize = 4 * 1024 * 1024
DefaultMaxRequestBodySize
是服務器默承認讀的最大請求體大小。併發
更多詳情請參閱 Server.MaxRequestBodySize
。
const FSCompressedFileSuffix = ".fasthttp.gz"
FSCompressedFileSuffix
是當須要使用新文件名存儲被壓縮後的文件時, FS
在原始文件名上添加的前綴。更多詳情請參閱 FS.Compress
。
const FSHandlerCacheDuration = 10 * time.Second
FSHandlerCacheDuration
是由 FS
所打開的非活躍文件句柄的默認失效時間。
變量
var (
ErrNoFreeConns = errors.New("no free connections available to host")
ErrTimeout = errors.New("timeout")
ErrConnectionClosed = errors.New("the server closed connection before returning the first response byte. " +
"Make sure the server returns 'Connection: close' response header before closing the connection")
)
var (
CookieExpireDelete = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
CookieExpireUnlimited = zeroTime
)
var (
ErrPerIPConnLimit = errors.New("too many connections per ip")
ErrConcurrencyLimit = errors.New("canot serve the connection because Server.Concurrency concurrent connections are served")
ErrKeepaliveTimeout = errors.New("exceeded MaxKeepaliveDuration")
)
var ErrBodyTooLarge = errors.New("body size exceeds the given limit")
ErrBodyTooLarge
會在請求體或者響應體超過指定限制時返回。
var ErrDialTimeout = errors.New("dialing to the given TCP address timed out")
ErrDialTimeout
會在 TCP 握手超時時觸發。
var ErrMissingFile = errors.New("there is no uploaded file associated with the given key")
ErrMissingFile
會在沒有與指定的 multipart
表單鍵相關聯的被上傳文件時由 FormFile
返回。
var ErrNoArgValue = errors.New("no Args value for the given key")
ErrNoArgValue
會在指定 Args
鍵缺乏值時返回。
var ErrNoMultipartForm = errors.New("request has no multipart/form-data Content-Type")
ErrNoMultipartForm
意味着請求的 Content-Type
不是 'multipart/form-data'
。
var ErrPipelineOverflow = errors.New("pipelined requests' queue has been overflown. Increase MaxConns and/or MaxPendingRequests")
ErrPipelineOverflow
會在請求的隊列溢出時,由 PipelineClient.Do*
函數族返回。
func AppendBytesStr
func AppendBytesStr(dst []byte, src string) []byte
AppendBytesStr
向 dst
追加 src
,而且返回追加後的 dst
。
這個函數與 append(dst, src...)
的性能沒有差異。目前它僅用於向後兼容。
這個函數已經棄用而且可能很快被移除。
func AppendGunzipBytes
func AppendGunzipBytes(dst, src []byte) ([]byte, error)
AppendGunzipBytes
向 dst
追加 gunzip 壓縮後的 src
,而且返回追加後的 dst
。
func AppendGzipBytes
func AppendGzipBytes(dst, src []byte) []byte
AppendGzipBytes
向 dst
追加 gzip 壓縮後的 src
,而且返回追加後的 dst
。
func AppendGzipBytesLevel
func AppendGzipBytesLevel(dst, src []byte, level int) []byte
AppendGzipBytesLevel
向 dst
追加指定級別的 gzip 壓縮後的 src
,而且返回追加後的 dst
。
支持的壓縮級別有:
CompressNoCompression
CompressBestSpeed
CompressBestCompression
CompressDefaultCompression
func AppendHTMLEscape
func AppendHTMLEscape(dst []byte, s string) []byte
AppendHTMLEscape
向 dst
追加 HTML 轉義後的 src
,而且返回追加後的 dst
。
func AppendHTMLEscapeBytes
func AppendHTMLEscapeBytes(dst, s []byte) []byte
AppendHTMLEscapeBytes
向 dst
追加 HTML 轉義後的 src
,而且返回追加後的 dst
。
func AppendHTTPDate
func AppendHTTPDate(dst []byte, date time.Time) []byte
AppendHTTPDate
向 dst
追加符合 HTTP-compliant (RFC1123) 表示的時間 ,而且返回追加後的 dst
。
func AppendIPv4
func AppendIPv4(dst []byte, ip net.IP) []byte
AppendIPv4
向 dst
追加表示 ip v4 的字符串 ,而且返回追加後的 dst
。
func AppendNormalizedHeaderKey
func AppendNormalizedHeaderKey(dst []byte, key string) []byte
AppendNormalizedHeaderKey
向 dst
追加標準化後的 HTTP 頭鍵(名),而且返回追加後的 dst
。
標準化後的頭鍵由一個大寫字母開頭。在 -
後的第一個字母也爲大寫。其餘的全部字母則都爲小寫。例子:
- coNTENT-TYPe -> Content-Type
- HOST -> Host
- foo-bar-baz -> Foo-Bar-Baz
func AppendNormalizedHeaderKeyBytes
func AppendNormalizedHeaderKeyBytes(dst, key []byte) []byte
AppendNormalizedHeaderKeyBytes
向 dst
追加標準化後的 HTTP 頭鍵(名),而且返回追加後的 dst
。
標準化後的頭鍵由一個大寫字母開頭。在 -
後的第一個字母也爲大寫。其餘的全部字母則都爲小寫。例子:
- coNTENT-TYPe -> Content-Type
- HOST -> Host
- foo-bar-baz -> Foo-Bar-Baz
func AppendQuotedArg
func AppendQuotedArg(dst, src []byte) []byte
AppendQuotedArg
向 dst
追加通過 url 加密的 src
,而且返回追加後的 dst
。
func AppendUint
func AppendUint(dst []byte, n int) []byte
AppendUint
向 dst
追加 n
,而且返回追加後的 dst
。
func Dial
func Dial(addr string) (net.Conn, error)
Dial
使用 tcp4 鏈接指定的 TCP 地址 addr
。
與 net.Dial
相比,該函數有如下這些額外的特性:
- 它經過以
DefaultDNSCacheDuration
持續時間緩存解析後的 TCP 地址來減小 DNS 解析器的負載。
- 它經過輪詢來鏈接全部被解析後的 TCP 鏈接,直至第一個鏈接被創建。這在當其中的某一個 TCP 地址臨時性不可用時至關有用。
- 在
DefaultDialTimeout
秒以後若鏈接尚未被創建,它會返回 ErrDialTimeout
,可使用DialTimeout
來自定義這個超時。
addr
參數必須包含端口,例如:
foobar.baz:443
foo.bar:80
aaa.com:8080
func DialDualStack
func DialDualStack(addr string) (net.Conn, error)
DialDualStack
使用 tcp4 和 tcp6 鏈接指定的 TCP 地址 addr
。
與 net.Dial
相比,該函數有如下這些額外的特性:
- 它經過以
DefaultDNSCacheDuration
持續時間緩存解析後的 TCP 地址來減小 DNS 解析器的負載。
- 它經過輪詢來鏈接全部被解析後的 TCP 鏈接,直至第一個鏈接被創建。這在當其中的某一個 TCP 地址臨時性不可用時至關有用。
- 在
DefaultDialTimeout
秒以後若鏈接尚未被創建,它會返回 ErrDialTimeout
,可使用DialTimeout
來自定義這個超時。
addr
參數必須包含端口,例如:
foobar.baz:443
foo.bar:80
aaa.com:8080
func DialDualStackTimeout
func DialDualStackTimeout(addr string, timeout time.Duration) (net.Conn, error)
DialDualStackTimeout
使用 tcp4 和 tcp6 鏈接指定的 TCP 地址 addr
,而且會在指定時間後超時。
與 net.Dial
相比,該函數有如下這些額外的特性:
- 它經過以
DefaultDNSCacheDuration
持續時間緩存解析後的 TCP 地址來減小 DNS 解析器的負載。
- 它經過輪詢來鏈接全部被解析後的 TCP 鏈接,直至第一個鏈接被創建。這在當其中的某一個 TCP 地址臨時性不可用時至關有用。
- 在
DefaultDialTimeout
秒以後若鏈接尚未被創建,它會返回 ErrDialTimeout
,可使用DialTimeout
來自定義這個超時。
addr
參數必須包含端口,例如:
foobar.baz:443
foo.bar:80
aaa.com:8080
func DialTimeout
func DialTimeout(addr string, timeout time.Duration) (net.Conn, error)
DialTimeout
使用 tcp4 和 tcp6 鏈接指定的 TCP 地址 addr
,而且會在指定時間後超時。
與 net.Dial
相比,該函數有如下這些額外的特性:
- 它經過以
DefaultDNSCacheDuration
持續時間緩存解析後的 TCP 地址來減小 DNS 解析器的負載。
- 它經過輪詢來鏈接全部被解析後的 TCP 鏈接,直至第一個鏈接被創建。這在當其中的某一個 TCP 地址臨時性不可用時至關有用。
- 在
DefaultDialTimeout
秒以後若鏈接尚未被創建,它會返回 ErrDialTimeout
,可使用DialTimeout
來自定義這個超時。
addr
參數必須包含端口,例如:
foobar.baz:443
foo.bar:80
aaa.com:8080
func Do
func Do(req *Request, resp *Response) error
Do
發出指定的 http 請求,在獲得響應後而且填充指定的 http 響應對象。
請求必須至少包含一個非空的 RequestURI (包含協議和 host)或非空的 Host 頭 + RequestURI。
客戶端以如下順序肯定待請求的服務端:
- 若是 RequestURI 包含完整的帶有協議和 host 的 url ,則從 RequestURI 中取得。
- 不然就從 Host 頭中取得。
這個函數不會跟隨重定向。若要跟隨重定向,請使用 Get*
。
若是 resp
是 nil
,那麼響應會被忽略。
若是向指定請求 host 的全部 DefaultMaxConnsPerHost
數量的鏈接都被佔用,那麼會返回 ErrNoFreeConns
。
在有性能要求的代碼中,推薦經過 AcquireRequest
和 AcquireResponse
來獲取 req
和 resp
。
func DoDeadline
func DoDeadline(req *Request, resp *Response, deadline time.Time) error
DoDeadline
發出指定的 http 請求,而且在指定的 deadline 以前獲得響應後填充指定的 http 響應對象。
請求必須至少包含一個非空的 RequestURI (包含協議和 host)或非空的 Host 頭 + RequestURI。
客戶端以如下順序肯定待請求的服務端:
- 若是 RequestURI 包含完整的帶有協議和 host 的 url ,則從 RequestURI 中取得。
- 不然就從 Host 頭中取得。
這個函數不會跟隨重定向。若要跟隨重定向,請使用 Get*
。
若是 resp
是 nil
,那麼響應會被忽略。
若是向指定請求 host 的全部 DefaultMaxConnsPerHost
數量的鏈接都被佔用,那麼會返回 ErrNoFreeConns
。
在有性能要求的代碼中,推薦經過 AcquireRequest
和 AcquireResponse
來獲取 req
和 resp
。
func DoTimeout
func DoTimeout(req *Request, resp *Response, timeout time.Duration) error
DoTimeout
發出指定的 http 請求,而且在指定的超時以前獲得響應後填充指定的 http 響應對象。
請求必須至少包含一個非空的 RequestURI (包含協議和 host)或非空的 Host 頭 + RequestURI。
客戶端以如下順序肯定待請求的服務端:
- 若是 RequestURI 包含完整的帶有協議和 host 的 url ,則從 RequestURI 中取得。
- 不然就從 Host 頭中取得。
這個函數不會跟隨重定向。若要跟隨重定向,請使用 Get*
。
若是 resp
是 nil
,那麼響應會被忽略。
若是向指定請求 host 的全部 DefaultMaxConnsPerHost
數量的鏈接都被佔用,那麼會返回 ErrNoFreeConns
。
在有性能要求的代碼中,推薦經過 AcquireRequest
和 AcquireResponse
來獲取 req
和 resp
。
func EqualBytesStr
func EqualBytesStr(b []byte, s string) bool
EqualBytesStr
,在 string(b) == s
時返回 true
。
這個函數與 string(b) == s
的性能沒有差異。目前它僅用於向後兼容。
這個函數已經棄用而且可能很快被移除。
func FileLastModified
func FileLastModified(path string) (time.Time, error)
FileLastModified
返回文件的最後修改時間。
func Get
func Get(dst []byte, url string) (statusCode int, body []byte, err error)
Get
向 dst
追加 url 信息,而且經過 body
返回它。
這個函數會跟隨重定向。若要手動操做重定向,請使用 Do*
。
若是 dst
爲 nil
,那麼則會分配一個新的 body
緩衝。
func GetDeadline
func GetDeadline(dst []byte, url string, deadline time.Time) (statusCode int, body []byte, err error)
GetDeadline
向 dst
追加 url 信息,而且經過 body
返回它。
這個函數會跟隨重定向。若要手動操做重定向,請使用 Do*
。
若是 dst
爲 nil
,那麼則會分配一個新的 body
緩衝。
若在指定的 deadline 以前沒能獲取到響應,那麼會返回 ErrTimeout
。
func GetTimeout
func GetTimeout(dst []byte, url string, timeout time.Duration) (statusCode int, body []byte, err error)
GetTimeout
向 dst
追加 url 信息,而且經過 body
返回它。
這個函數會跟隨重定向。若要手動操做重定向,請使用 Do*
。
若是 dst
爲 nil
,那麼則會分配一個新的 body
緩衝。
若在指定的超時以前沒能獲取到響應,那麼會返回 ErrTimeout
。
func ListenAndServe
func ListenAndServe(addr string, handler RequestHandler) error
ListenAndServe
使用指定的 handler
處理來自指定 TCP 地址 addr
的 HTTP 請求。
例子:
listenAddr := "127.0.0.1:80"
requestHandler := func(ctx *fasthttp.RequestCtx) {
fmt.Fprintf(ctx, "Hello, world! Requested path is %q", ctx.Path())
}
if err := fasthttp.ListenAndServe(listenAddr, requestHandler); err != nil {
log.Fatalf("error in ListenAndServe: %s", err)
}
func ListenAndServeTLS
func ListenAndServeTLS(addr, certFile, keyFile string, handler RequestHandler) error
ListenAndServeTLS
使用指定的 handler
處理來自指定 TCP 地址 addr
的 HTTPS 請求。
certFile
和 keyFile
是 TLS 證書和密鑰文件的路徑。
func ListenAndServeTLSEmbed
func ListenAndServeTLSEmbed(addr string, certData, keyData []byte, handler RequestHandler) error
ListenAndServeTLSEmbed
使用指定的 handler
處理來自指定 TCP 地址 addr
的 HTTPS 請求。
certData
和 keyData
必須包含合法的 TLS 證書和密鑰數據。
func ListenAndServeUNIX
func ListenAndServeUNIX(addr string, mode os.FileMode, handler RequestHandler) error
ListenAndServeUNIX
使用指定的 handler
處理來自指定 UNIX 地址 addr
的 HTTP 請求。
這個函數會在開始接受請求前刪除全部 addr
下的文件。
該函數會爲制定 UNIX 地址 addr
設置參數中指定的 mode
。
func NewStreamReader
func NewStreamReader(sw StreamWriter) io.ReadCloser
NewStreamReader
返回一個 reader
,用於獲取全部由 sw
生成的數據。
返回的 reader
能夠被傳遞至 Response.SetBodyStream
。
在返回的 reader
中全部的數據都被讀取完畢以後,必須調用 Close
。不然可能會形成 goroutine 泄露。
更多詳情可參閱 Response.SetBodyStreamWriter
。
func ParseByteRange
func ParseByteRange(byteRange []byte, contentLength int) (startPos, endPos int, err error)
ParseByteRange
用於解釋 'Range: bytes=...'
頭的值。
依據的規範是 https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 。
func ParseHTTPDate
func ParseHTTPDate(date []byte) (time.Time, error)
ParseHTTPDate
用於解釋符合 HTTP-compliant (RFC1123) 規範的時間。
func ParseIPv4
func ParseIPv4(dst net.IP, ipStr []byte) (net.IP, error)
ParseIPv4
解釋 ipStr
提供的 ip 地址,並填充 dst
,而後返回填充後的 dst
。
func ParseUfloat
func ParseUfloat(buf []byte) (float64, error)
ParseUfloat
解釋 buf
提供的無符號浮點數。
func ParseUint
func ParseUint(buf []byte) (int, error)
ParseUint
解釋 buf
提供的無符號整型數。
func Post
func Post(dst []byte, url string, postArgs *Args) (statusCode int, body []byte, err error)
Post
使用指定 POST 參數向指定 url
發出 POST 請求。
請求體會追加值 dst
,而且經過 body
返回。
這個函數會跟隨重定向。若要手動操做重定向,請使用 Do*
。
若 dst
是 nil
,那麼新的 body
緩衝會被分配。
若是 postArgs
是 nil
,則發送空 POST 請求體。
func ReleaseArgs
func ReleaseArgs(a *Args)
ReleaseArgs
向池中釋放經過 AquireArgs
取得的對象。
不要試圖訪問釋放的 Args
對象,可能會產生數據競爭。
func ReleaseByteBuffer
func ReleaseByteBuffer(b *ByteBuffer)
ReleaseByteBuffer
返回池中釋放指定字節緩衝。
在釋放回池以後, ByteBuffer.B
不能再被訪問,可能會產生數據競爭。
func ReleaseCookie
func ReleaseCookie(c *Cookie)
ReleaseCookie
向池中釋放由 AcquireCookie
返回的對象。
不要試圖訪問釋放的 Cookie
對象,可能會產生數據競爭。
func ReleaseRequest
func ReleaseRequest(req *Request)
ReleaseRequest
向池中釋放由 AcquireRequest
返回的對象。
在釋放回池以後,禁止再訪問 req
對象以及它的任何成員。
func ReleaseResponse
func ReleaseResponse(resp *Response)
ReleaseResponse
向池中釋放由 AcquireResponse
返回的對象。
在釋放回池以後,禁止再訪問 resp
對象以及它的任何成員。
func ReleaseURI
func ReleaseURI(u *URI)
ReleaseURI
向池中釋放由 AcquireURI
返回的對象。
不要試圖訪問釋放的 URI
對象,可能會產生數據競爭。
func SaveMultipartFile
func SaveMultipartFile(fh *multipart.FileHeader, path string) error
SaveMultipartFile
在指定的 path
下保存文件 fh
。
func Serve
func Serve(ln net.Listener, handler RequestHandler) error
Serve
使用指定的 handler
來處理來自 listener
的鏈接。
在 listener
返回永久性的錯誤以前, Serve
都會一直保持阻塞。
例子:
ln, err := net.Listen("tcp4", "127.0.0.1:8080")
if err != nil {
log.Fatalf("error in net.Listen: %s", err)
}
requestHandler := func(ctx *fasthttp.RequestCtx) {
fmt.Fprintf(ctx, "Hello, world! Requested path is %q", ctx.Path())
}
if err := fasthttp.Serve(ln, requestHandler); err != nil {
log.Fatalf("error in Serve: %s", err)
}
func ServeConn
func ServeConn(c net.Conn, handler RequestHandler) error
ServeConn
使用指定的 handler
處理來自指定鏈接的 HTTP 請求。
若是全部來自 c
的請求都被成功處理,ServeConn
會返回 nil
。不然返回一個非空錯誤。
鏈接 c
必須馬上將全部數據經過 Write()
發送至客戶端,不然請求的處理可能會被掛起。
ServeConn
在返回以前會關閉 c
。
func ServeFile
func ServeFile(ctx *RequestCtx, path string)
ServeFile
返回來自指定 path
的壓縮後文件內容的 HTTP 響應。
在如下狀況下,HTTP 響應可能會包含未壓縮文件內容:
- 缺乏
'Accept-Encoding: gzip'
請求頭。
- 沒有對文件目錄的寫權限。
若是 path
指向一個目錄,那麼目錄的內容會被返回。
若是你不須要響應壓縮後的文件內容,請使用 ServeFileUncompressed
。
更多詳情可參閱 RequestCtx.SendFile
。
func ServeFileBytes
func ServeFileBytes(ctx *RequestCtx, path []byte)
ServeFileBytes
返回來自指定 path
的壓縮後文件內容的 HTTP 響應。
在如下狀況下,HTTP 響應可能會包含未壓縮文件內容:
- 缺乏
'Accept-Encoding: gzip'
請求頭。
- 沒有對文件目錄的寫權限。
若是 path
指向一個目錄,那麼目錄的內容會被返回。
若是你不須要響應壓縮後的文件內容,請使用 ServeFileUncompressed
。
更多詳情可參閱 RequestCtx.SendFile
。
func ServeFileBytesUncompressed
func ServeFileBytesUncompressed(ctx *RequestCtx, path []byte)
ServeFileBytesUncompressed
返回來自指定 path
文件內容的 HTTP 響應。
若是 path
指向一個目錄,那麼目錄的內容會被返回。
若須要處理壓縮後的文件,請使用 ServeFileBytes
。
更多詳情可參閱 RequestCtx.SendFileBytes
。
func ServeFileUncompressed
func ServeFileUncompressed(ctx *RequestCtx, path string)
ServeFileUncompressed
返回來自指定 path
文件內容的 HTTP 響應。
若是 path
指向一個目錄,那麼目錄的內容會被返回。
若須要處理壓縮後的文件,請使用 ServeFile
。
更多詳情可參閱 RequestCtx.SendFile
。
func ServeTLS
func ServeTLS(ln net.Listener, certFile, keyFile string, handler RequestHandler) error
ServeTLS
使用指定的 handler
來處理來自指定 net.Listener
的 HTTPS 請求。
certFile
和 keyFile
是 TLS 證書和密鑰文件的路徑。
func ServeTLSEmbed
func ServeTLSEmbed(ln net.Listener, certData, keyData []byte, handler RequestHandler) error
ServeTLSEmbed
使用指定的 handler
來處理來自指定 net.Listener
的 HTTPS 請求。
certData
和 keyData
必須包含合法的 TLS 證書和密鑰數據。
func StatusMessage
func StatusMessage(statusCode int) string
StatusMessage
根據指定的狀態碼返回 HTTP 狀態信息。
func WriteGunzip
func WriteGunzip(w io.Writer, p []byte) (int, error)
WriteGunzip
向 w
寫入經 gunzip 壓縮的 p
,而且返回未壓縮的字節數。
func WriteGzip
func WriteGzip(w io.Writer, p []byte) (int, error)
WriteGunzip
向 w
寫入經 gzip 壓縮的 p
,而且返回未壓縮的字節數。
func WriteGzipLevel
func WriteGzipLevel(w io.Writer, p []byte, level int) (int, error)
WriteGunzip
向 w
寫入經指定級別 gzip 壓縮的 p
,而且返回未壓縮的字節數。
支持的壓縮級別有:
CompressNoCompression
CompressBestSpeed
CompressBestCompression
CompressDefaultCompression
func WriteInflate
func WriteInflate(w io.Writer, p []byte) (int, error)
WriteGunzip
向 w
寫入壓縮後的 p
,而且返回未壓縮的字節數。
func WriteMultipartForm
func WriteMultipartForm(w io.Writer, f *multipart.Form, boundary string) error
WriteMultipartForm
使用指定的 w
寫入指定的表單 f
。
type Args
type Args struct {
}
Args
表明查詢字符串參數。
拷貝 Args
實例是禁止的。你須要使用 CopyTo()
函數或建立一個新實例。
Args
實例必須不能在併發執行的 goroutine 間使用。
func AcquireArgs
func AcquireArgs() *Args
AcquireArgs
從池中返回一個空的 Args
對象。
返回的 Args
實例在再也不須要時能夠經過 ReleaseArgs
釋放回池。這能夠下降垃圾回收負載。
func (*Args) Add
func (a *Args) Add(key, value string)
Add
添加 'key=value'
參數。
同一個 key
能夠添加多個值。
func (*Args) AddBytesK
func (a *Args) AddBytesK(key []byte, value string)
AddBytesK
添加 'key=value'
參數。
同一個 key
能夠添加多個值。
func (*Args) AddBytesKV
func (a *Args) AddBytesKV(key, value []byte)
AddBytesKV
添加 'key=value'
參數。
同一個 key
能夠添加多個值。
func (*Args) AddBytesV
func (a *Args) AddBytesV(key string, value []byte)
AddBytesV
添加 'key=value'
參數。
同一個 key
能夠添加多個值。
func (*Args) AppendBytes
func (a *Args) AppendBytes(dst []byte) []byte
AppendBytes
像 dst
追加查詢字符串,並返回 dst
。
func (*Args) CopyTo
func (a *Args) CopyTo(dst *Args)
CopyTo
將全部的參數複製至 dst
。
func (*Args) Del
func (a *Args) Del(key string)
Del
刪除鍵爲指定 key
的參數。
func (*Args) DelBytes
func (a *Args) DelBytes(key []byte)
Del
刪除鍵爲指定 key
的參數。
func (*Args) GetUfloat
func (a *Args) GetUfloat(key string) (float64, error)
GetUfloat
返回指定 key
的無符號浮點數值。
func (*Args) GetUfloatOrZero
func (a *Args) GetUfloatOrZero(key string) float64
GetUfloatOrZero
返回指定 key
的無符號浮點數值。
當出錯時返回 0
。
func (*Args) GetUint
func (a *Args) GetUint(key string) (int, error)
GetUint
返回指定 key
的無符號整型數值。
func (*Args) GetUintOrZero
func (a *Args) GetUintOrZero(key string) int
GetUintOrZero
返回指定 key
的無符號整型數值。
當出錯時返回 0
。
func (*Args) Has
func (a *Args) Has(key string) bool
Has
在當 Args
中存在指定 key
時返回 true
。
func (*Args) HasBytes
func (a *Args) HasBytes(key []byte) bool
HasBytes
在當 Args
中存在指定 key
時返回 true
。
func (*Args) Len
func (a *Args) Len() int
Len
查詢參數的數量。
func (*Args) Parse
func (a *Args) Parse(s string)
Parse
解析包含查詢參數的字符串。
func (*Args) ParseBytes
func (a *Args) ParseBytes(b []byte)
ParseBytes
解析包含查詢參數的 b
。
func (*Args) Peek
func (a *Args) Peek(key string) []byte
Peek
返回查詢參數中指定 key
的值。
func (*Args) PeekBytes
func (a *Args) PeekBytes(key []byte) []byte
PeekBytes
返回查詢參數中指定 key
的值。
func (*Args) PeekMulti
func (a *Args) PeekMulti(key string) [][]byte
PeekMulti
返回查詢參數中指定 key
的全部值。
func (*Args) PeekMultiBytes
func (a *Args) PeekMultiBytes(key []byte) [][]byte
PeekMultiBytes
返回查詢參數中指定 key
的全部值。
func (*Args) QueryString
func (a *Args) QueryString() []byte
QueryString
返回查詢參數的字符串表示。
在下個 Args
方法調用以前,返回值都是合法的。
func (*Args) Reset
func (a *Args) Reset()
Reset
清除全部查詢參數。
func (*Args) Set
func (a *Args) Set(key, value string)
Set
設置 'key=value'
參數。
func (*Args) SetBytesK
func (a *Args) SetBytesK(key []byte, value string)
SetBytesK
設置 'key=value'
參數。
func (*Args) SetBytesKV
func (a *Args) SetBytesKV(key, value []byte)
SetBytesKV
設置 'key=value'
參數。
func (*Args) SetBytesV
func (a *Args) SetBytesV(key string, value []byte)
SetBytesV
設置 'key=value'
參數。
func (*Args) SetUint
func (a *Args) SetUint(key string, value int)
SetUint
爲指定 key
設置無符號整數值。
func (*Args) SetUintBytes
func (a *Args) SetUintBytes(key []byte, value int)
SetUintBytes
爲指定 key
設置無符號整數值。
func (*Args) String
func (a *Args) String() string
String
返回查詢參數的字符串表示。
func (*Args) VisitAll
func (a *Args) VisitAll(f func(key, value []byte))
VisitAll
對每個存在的參數調用 f
。
f
在返回後必須不能保留對鍵和值的引用。若要在返回後扔須要存儲它們,請存儲它們的副本。
func (*Args) WriteTo
func (a *Args) WriteTo(w io.Writer) (int64, error)
WriteTo
向 w
寫入查詢字符串。
WriteTo
實現了 io.WriterTo
接口。
type Client
type Client struct {
Name string
Dial DialFunc
DialDualStack bool
TLSConfig *tls.Config
MaxConnsPerHost int
MaxIdleConnDuration time.Duration
ReadBufferSize int
WriteBufferSize int
ReadTimeout time.Duration
WriteTimeout time.Duration
MaxResponseBodySize int
DisableHeaderNamesNormalizing bool
}
Client
實現了 HTTP 客戶端。
不容許按值拷貝 Client
,應該建立一個新的實例。
在多個運行的 goroutine 間調用 Client
方法是安全的。
func (*Client) Do
func (c *Client) Do(req *Request, resp *Response) error
Do
發出指定的 http 請求,在獲得響應後而且填充指定的 http 響應對象。
請求必須至少包含一個非空的 RequestURI (包含協議和 host)或非空的 Host 頭 + RequestURI。
客戶端以如下順序肯定待請求的服務端:
- 若是 RequestURI 包含完整的帶有協議和 host 的 url ,則從 RequestURI 中取得。
- 不然就從 Host 頭中取得。
若是 resp
是 nil
,那麼響應會被忽略。
這個函數不會跟隨重定向。若要跟隨重定向,請使用 Get*
。
若是向指定請求 host 的全部 DefaultMaxConnsPerHost
數量的鏈接都被佔用,那麼會返回 ErrNoFreeConns
。
在有性能要求的代碼中,推薦經過 AcquireRequest
和 AcquireResponse
來獲取 req
和 resp
。
func (*Client) DoDeadline
func (c *Client) DoDeadline(req *Request, resp *Response, deadline time.Time) error
DoDeadline
發出指定的 http 請求,而且在指定的 deadline 以前獲得響應後填充指定的 http 響應對象。
請求必須至少包含一個非空的 RequestURI (包含協議和 host)或非空的 Host 頭 + RequestURI。
客戶端以如下順序肯定待請求的服務端:
- 若是 RequestURI 包含完整的帶有協議和 host 的 url ,則從 RequestURI 中取得。
- 不然就從 Host 頭中取得。
這個函數不會跟隨重定向。若要跟隨重定向,請使用 Get*
。
若是 resp
是 nil
,那麼響應會被忽略。
若是向指定請求 host 的全部 DefaultMaxConnsPerHost
數量的鏈接都被佔用,那麼會返回 ErrNoFreeConns
。
在有性能要求的代碼中,推薦經過 AcquireRequest
和 AcquireResponse
來獲取 req
和 resp
。
func (*Client) DoTimeout
func (c *Client) DoTimeout(req *Request, resp *Response, timeout time.Duration) error
DoTimeout
發出指定的 http 請求,而且在指定的超時以前獲得響應後填充指定的 http 響應對象。
請求必須至少包含一個非空的 RequestURI (包含協議和 host)或非空的 Host 頭 + RequestURI。
客戶端以如下順序肯定待請求的服務端:
- 若是 RequestURI 包含完整的帶有協議和 host 的 url ,則從 RequestURI 中取得。
- 不然就從 Host 頭中取得。
這個函數不會跟隨重定向。若要跟隨重定向,請使用 Get*
。
若是 resp
是 nil
,那麼響應會被忽略。
若是向指定請求 host 的全部 DefaultMaxConnsPerHost
數量的鏈接都被佔用,那麼會返回 ErrNoFreeConns
。
在有性能要求的代碼中,推薦經過 AcquireRequest
和 AcquireResponse
來獲取 req
和 resp
。
func (*Client) Get
func (c *Client) Get(dst []byte, url string) (statusCode int, body []byte, err error)
Get
向 dst
追加 url 信息,而且經過 body
返回它。
這個函數會跟隨重定向。若要手動操做重定向,請使用 Do*
。
若是 dst
爲 nil
,那麼則會分配一個新的 body
緩衝。
func (*Client) GetDeadline
func (c *Client) GetDeadline(dst []byte, url string, deadline time.Time) (statusCode int, body []byte, err error)
GetDeadline
向 dst
追加 url 信息,而且經過 body
返回它。
這個函數會跟隨重定向。若要手動操做重定向,請使用 Do*
。
若是 dst
爲 nil
,那麼則會分配一個新的 body
緩衝。
若在指定的 deadline 以前沒能獲取到響應,那麼會返回 ErrTimeout
。
func (*Client) GetTimeout
func (c *Client) GetTimeout(dst []byte, url string, timeout time.Duration) (statusCode int, body []byte, err error)
GetTimeout
向 dst
追加 url 信息,而且經過 body
返回它。
這個函數會跟隨重定向。若要手動操做重定向,請使用 Do*
。
若是 dst
爲 nil
,那麼則會分配一個新的 body
緩衝。
若在指定的超時以前沒能獲取到響應,那麼會返回 ErrTimeout
。
func (*Client) Post
func (c *Client) Post(dst []byte, url string, postArgs *Args) (statusCode int, body []byte, err error)
Post
使用指定 POST 參數向指定 url
發出 POST 請求。
請求體會追加值 dst
,而且經過 body
返回。
這個函數會跟隨重定向。若要手動操做重定向,請使用 Do*
。
若 dst
是 nil
,那麼新的 body
緩衝會被分配。
若是 postArgs
是 nil
,則發送空 POST 請求體。
type Cookie
type Cookie struct {
}
Cookie
表明 HTTP 相應的 cookie 。
不容許按值拷貝 Cookie
,應該建立一個新的實例。
在多個運行的 goroutine 間使用 Cookie
實例是禁止的。
func AcquireCookie
func AcquireCookie() *Cookie
AcquireCookie
從池中返回一個空的 Cookie
對象。
返回的 Cookie
實例在再也不須要時能夠經過 ReleaseCookie
釋放回池。這能夠下降垃圾回收負載。
func (*Cookie) AppendBytes
func (c *Cookie) AppendBytes(dst []byte) []byte
AppendBytes
向 dst
追加 cookie ,而且返回追加後的 dst
。
func (*Cookie) Cookie
func (c *Cookie) Cookie() []byte
Cookie
返回 cookie 的表示。
直到下次調用 Cookie
方法前,返回值都是合法的。
func (*Cookie) CopyTo
func (c *Cookie) CopyTo(src *Cookie)
CopyTo
拷貝 src
cookie 至 c
。
func (*Cookie) Domain
func (c *Cookie) Domain() []byte
Domain
返回 cookie 的 domain 值。
直到下次調用會改變 Cookie
的方法前,返回值都是合法的。
func (*Cookie) Expire
func (c *Cookie) Expire() time.Time
Expire
返回 cookie 的過時時間。
若沒設置過時,則返回 CookieExpireUnlimited
。
func (*Cookie) HTTPOnly
func (c *Cookie) HTTPOnly() bool
HTTPOnly
在 cookie 爲 http only 時返回 true
。
func (*Cookie) Key
func (c *Cookie) Key() []byte
Key
返回 cookie 名字。
直到下次調用會改變 Cookie
的方法前,返回值都是合法的。
func (*Cookie) Parse
func (c *Cookie) Parse(src string) error
Parse
解析 Set-Cookie 頭。
func (*Cookie) ParseBytes
func (c *Cookie) ParseBytes(src []byte) error
ParseBytes
解析 Set-Cookie 頭。
func (*Cookie) Path
func (c *Cookie) Path() []byte
Path
返回 cookie path 。
func (*Cookie) Reset
func (c *Cookie) Reset()
Reset
清空該 cookie 。
func (*Cookie) Secure
func (c *Cookie) Secure() bool
Secure
在當 cookie 爲 secure 時返回 true
。
func (*Cookie) SetDomain
func (c *Cookie) SetDomain(domain string)
SetDomain
設置 cookie 的 domain 。
func (*Cookie) SetDomainBytes
func (c *Cookie) SetDomainBytes(domain []byte)
SetDomainBytes
設置 cookie 的 domain 。
func (*Cookie) SetExpire
func (c *Cookie) SetExpire(expire time.Time)
SetExpire
設置 cookie 的過時時間。
若要使該 cookie 在客戶端過時,則將值設置爲 CookieExpireDelete
。
默認狀況下 cookie 的壽命由瀏覽器會話限制。
func (*Cookie) SetHTTPOnly
func (c *Cookie) SetHTTPOnly(httpOnly bool)
SetHTTPOnly
將 cookie 的 httpOnly 標識設置爲指定值。
func (*Cookie) SetKey
func (c *Cookie) SetKey(key string)
SetKey
設置 cookie 名。
func (*Cookie) SetKeyBytes
func (c *Cookie) SetKeyBytes(key []byte)
SetKeyBytes
設置 cookie 名。
func (*Cookie) SetPath
func (c *Cookie) SetPath(path string)
SetPath
設置 cookie 路徑。
func (*Cookie) SetPathBytes
func (c *Cookie) SetPathBytes(path []byte)
SetPathBytes
設置 cookie 路徑。
func (*Cookie) SetSecure
func (c *Cookie) SetSecure(secure bool)
SetSecure
將 cookie 的 secure 標識設置爲指定值。
func (*Cookie) SetValue
func (c *Cookie) SetValue(value string)
SetValue
設置 cookie 的值。
func (*Cookie) SetValueBytes
func (c *Cookie) SetValueBytes(value []byte)
SetValueBytes
設置 cookie 的值。
func (*Cookie) String
func (c *Cookie) String() string
String
返回 cookie 的字符串表示。
func (*Cookie) Value
func (c *Cookie) Value() []byte
Value
返回 cookie 的值。
直到下次調用會改變 Cookie
的方法前,返回值都是合法的。
func (*Cookie) WriteTo
func (c *Cookie) WriteTo(w io.Writer) (int64, error)
WriteTo
將 cookie 的字符串表示寫入 w
。
WriteTo
實現了 io.WriterTo
接口。
type DialFunc
type DialFunc func(addr string) (net.Conn, error)
DialFunc
必須創建到 addr
的鏈接。
沒有必要爲 HTTPS 創建到 TLS(SSL)的鏈接。若 HostClient.IsTLS
被設置,則客戶端會自動轉換鏈接至 TLS 。
TCP address passed to DialFunc always contains host and port. Example TCP addr values: 傳遞至DialFunc
的 TCP 地址老是包含 host 和端口。例子:
foobar.com:80
foobar.com:443
foobar.com:8080
type FS
type FS struct {
Root string
IndexNames []string
GenerateIndexPages bool
Compress bool
AcceptByteRange bool
PathRewrite PathRewriteFunc
CacheDuration time.Duration
CompressedFileSuffix string
}
FS
表明了經過本地文件系統來響應靜態文件 HTTP 請求的設置。
不容許複製 FS
值,應該建立新的 FS
值。
例子:
fs := &fasthttp.FS{
Root: "/var/www/static-site",
GenerateIndexPages: true,
Compress: true,
}
h := fs.NewRequestHandler()
if err := fasthttp.ListenAndServe(":8080", h); err != nil {
log.Fatalf("error in ListenAndServe: %s", err)
}
func (*FS) NewRequestHandler
func (fs *FS) NewRequestHandler() RequestHandler
NewRequestHandler
經過指定的 FS
設置返回新的請求 handler 。
返回的 handler 根據 FS.CacheDuration
來緩存請求的文件句柄。若 FS.Root
目錄包含大量文件,請確保你的程序經過 'ulimit -n'
來保證有足夠的「可打開文件」。
不須要對單個 FS
實例建立多個請求 handler ,只需重用便可。
type HijackHandler
type HijackHandler func(c net.Conn)
HijackHandler
必須處理攔截的鏈接 c
。
在 HijackHandler
返回後鏈接 c
會被自動關閉。
在 HijackHandler
返回後鏈接 c
必須不可再被使用。
type HostClient
type HostClient struct {
Addr string
Name string
Dial DialFunc
DialDualStack bool
IsTLS bool
TLSConfig *tls.Config
MaxConns int
MaxConnDuration time.Duration
MaxIdleConnDuration time.Duration
ReadBufferSize int
WriteBufferSize int
ReadTimeout time.Duration
WriteTimeout time.Duration
MaxResponseBodySize int
DisableHeaderNamesNormalizing bool
}
HostClient
均衡地向列於 Addr
中的 host 發起請求。
禁止拷貝 HostClient
實例。應使用建立新的實例。
在多個運行的 goroutine 間執行 HostClient
方法是安全的。
例子:
package main
import (
"log""github.com/valyala/fasthttp"
)
func main() {
c := &fasthttp.HostClient{
Addr: "localhost:8080",
}
statusCode, body, err := c.Get(nil, "http://google.com/foo/bar")
if err != nil {
log.Fatalf("Error when loading google page through local proxy: %s", err)
}
if statusCode != fasthttp.StatusOK {
log.Fatalf("Unexpected status code: %d. Expecting %d", statusCode, fasthttp.StatusOK)
}
useResponseBody(body)
statusCode, body, err = c.Get(body, "http://foobar.com/google/com")
if err != nil {
log.Fatalf("Error when loading foobar page through local proxy: %s", err)
}
if statusCode != fasthttp.StatusOK {
log.Fatalf("Unexpected status code: %d. Expecting %d", statusCode, fasthttp.StatusOK)
}
useResponseBody(body)
}
func useResponseBody(body []byte) {
}
func (*HostClient) Do
func (c *HostClient) Do(req *Request, resp *Response) error
Do
發出指定的 http 請求,在獲得響應後而且填充指定的 http 響應對象。
請求必須至少包含一個非空的 RequestURI (包含協議和 host)或非空的 Host 頭 + RequestURI。
客戶端以如下順序肯定待請求的服務端:
- 若是 RequestURI 包含完整的帶有協議和 host 的 url ,則從 RequestURI 中取得。
- 不然就從 Host 頭中取得。
這個函數不會跟隨重定向。若要跟隨重定向,請使用 Get*
。
若是 resp
是 nil
,那麼響應會被忽略。
若是向指定請求 host 的全部 DefaultMaxConnsPerHost
數量的鏈接都被佔用,那麼會返回 ErrNoFreeConns
。
在有性能要求的代碼中,推薦經過 AcquireRequest
和 AcquireResponse
來獲取 req
和 resp
。
func (*HostClient) DoDeadline
func (c *HostClient) DoDeadline(req *Request, resp *Response, deadline time.Time) error
DoDeadline
發出指定的 http 請求,而且在指定的 deadline 以前獲得響應後填充指定的 http 響應對象。
請求必須至少包含一個非空的 RequestURI (包含協議和 host)或非空的 Host 頭 + RequestURI。
客戶端以如下順序肯定待請求的服務端:
- 若是 RequestURI 包含完整的帶有協議和 host 的 url ,則從 RequestURI 中取得。
- 不然就從 Host 頭中取得。
這個函數不會跟隨重定向。若要跟隨重定向,請使用 Get*
。
若是 resp
是 nil
,那麼響應會被忽略。
若是向指定請求 host 的全部 DefaultMaxConnsPerHost
數量的鏈接都被佔用,那麼會返回 ErrNoFreeConns
。
在有性能要求的代碼中,推薦經過 AcquireRequest
和 AcquireResponse
來獲取 req
和 resp
。
func (*HostClient) DoTimeout
func (c *HostClient) DoTimeout(req *Request, resp *Response, timeout time.Duration) error
DoTimeout
發出指定的 http 請求,而且在指定的超時以前獲得響應後填充指定的 http 響應對象。
請求必須至少包含一個非空的 RequestURI (包含協議和 host)或非空的 Host 頭 + RequestURI。
客戶端以如下順序肯定待請求的服務端:
- 若是 RequestURI 包含完整的帶有協議和 host 的 url ,則從 RequestURI 中取得。
- 不然就從 Host 頭中取得。
這個函數不會跟隨重定向。若要跟隨重定向,請使用 Get*
。
若是 resp
是 nil
,那麼響應會被忽略。
若是向指定請求 host 的全部 DefaultMaxConnsPerHost
數量的鏈接都被佔用,那麼會返回 ErrNoFreeConns
。
在有性能要求的代碼中,推薦經過 AcquireRequest
和 AcquireResponse
來獲取 req
和 resp
。
func (*HostClient) Get
func (c *HostClient) Get(dst []byte, url string) (statusCode int, body []byte, err error)
Get
向 dst
追加 url 信息,而且經過 body
返回它。
這個函數會跟隨重定向。若要手動操做重定向,請使用 Do*
。
若是 dst
爲 nil
,那麼則會分配一個新的 body
緩衝。
func (*HostClient) GetDeadline
func (c *HostClient) GetDeadline(dst []byte, url string, deadline time.Time) (statusCode int, body []byte, err error)
GetDeadline
向 dst
追加 url 信息,而且經過 body
返回它。
這個函數會跟隨重定向。若要手動操做重定向,請使用 Do*
。
若是 dst
爲 nil
,那麼則會分配一個新的 body
緩衝。
若在指定的 deadline 以前沒能獲取到響應,那麼會返回 ErrTimeout
。
func (*HostClient) GetTimeout
func (c *HostClient) GetTimeout(dst []byte, url string, timeout time.Duration) (statusCode int, body []byte, err error)
GetTimeout
向 dst
追加 url 信息,而且經過 body
返回它。
這個函數會跟隨重定向。若要手動操做重定向,請使用 Do*
。
若是 dst
爲 nil
,那麼則會分配一個新的 body
緩衝。
若在指定的超時以前沒能獲取到響應,那麼會返回 ErrTimeout
。
func (*HostClient) LastUseTime
func (c *HostClient) LastUseTime() time.Time
LastUseTime
返回客戶端最後被使用的時間。
func (*HostClient) PendingRequests
func (c *HostClient) PendingRequests() int
PendingRequests
返回正在執行的請求數。
func (*HostClient) Post
func (c *HostClient) Post(dst []byte, url string, postArgs *Args) (statusCode int, body []byte, err error)
Post
使用指定 POST 參數向指定 url
發出 POST 請求。
請求體會追加值 dst
,而且經過 body
返回。
這個函數會跟隨重定向。若要手動操做重定向,請使用 Do*
。
若 dst
是 nil
,那麼新的 body
緩衝會被分配。
若是 postArgs
是 nil
,則發送空 POST 請求體。
type Logger
type Logger interface {
Printf(format string, args ...interface{})
}
Logger
被用於記錄格式化信息日誌。
type PathRewriteFunc
type PathRewriteFunc func(ctx *RequestCtx) []byte
PathRewriteFunc
必須返回基於 ctx.Path()
的新請求路徑。
該函數用於在 FS
中轉義當前請求路徑至相對於 FS.Root
的相對路徑。
處於安全緣由,返回的路徑中不容許包含 '/../'
子字符串。
func NewPathPrefixStripper
func NewPathPrefixStripper(prefixSize int) PathRewriteFunc
NewPathPrefixStripper
返回重寫路徑函數,返回移除的前綴大小。
例子:
- prefixSize = 0, 原路徑: "/foo/bar", 結果: "/foo/bar"
- prefixSize = 3, 原路徑: "/foo/bar", 結果: "o/bar"
- prefixSize = 7, 原路徑: "/foo/bar", 結果: "r"
返回的路徑重寫函數可能會被 FS.PathRewrite
使用。
func NewPathSlashesStripper
func NewPathSlashesStripper(slashesCount int) PathRewriteFunc
NewPathSlashesStripper
返回重寫路徑函數,返回移除的路徑分隔符數量。
例子:
- slashesCount = 0, 原路徑: "/foo/bar", 結果: "/foo/bar"
- slashesCount = 1, 原路徑: "/foo/bar", 結果: "/bar"
- slashesCount = 2, 原路徑: "/foo/bar", 結果: ""
返回的路徑重寫函數可能會被 FS.PathRewrite
使用。
type PipelineClient
type PipelineClient struct {
Addr string
MaxConns int
MaxPendingRequests int
MaxBatchDelay time.Duration
Dial DialFunc
DialDualStack bool
IsTLS bool
TLSConfig *tls.Config
MaxIdleConnDuration time.Duration
ReadBufferSize int
WriteBufferSize int
ReadTimeout time.Duration
WriteTimeout time.Duration
Logger Logger
}
PipelineClient
經過一個指定的併發鏈接限制數,來發送請求。
這個客戶端可能被用於高負載的 RPC 系統。更多詳情參閱 https://en.wikipedia.org/wiki/HTTP_pipelining 。
禁止拷貝 PipelineClient
實例。應該建立新實例。
在運行的 goroutine 間調用 PipelineClient
方法是安全的。
func (*PipelineClient) Do
func (c *PipelineClient) Do(req *Request, resp *Response) error
Do
發出指定的 http 請求,在獲得響應後而且填充指定的 http 響應對象。
請求必須至少包含一個非空的 RequestURI (包含協議和 host)或非空的 Host 頭 + RequestURI。
客戶端以如下順序肯定待請求的服務端:
- 若是 RequestURI 包含完整的帶有協議和 host 的 url ,則從 RequestURI 中取得。
- 不然就從 Host 頭中取得。
這個函數不會跟隨重定向。若要跟隨重定向,請使用 Get*
。
若是 resp
是 nil
,那麼響應會被忽略。
若是向指定請求 host 的全部 DefaultMaxConnsPerHost
數量的鏈接都被佔用,那麼會返回 ErrNoFreeConns
。
在有性能要求的代碼中,推薦經過 AcquireRequest
和 AcquireResponse
來獲取 req
和 resp
。
func (*PipelineClient) DoDeadline
func (c *PipelineClient) DoDeadline(req *Request, resp *Response, deadline time.Time) error
DoDeadline
發出指定的 http 請求,而且在指定的 deadline 以前獲得響應後填充指定的 http 響應對象。
請求必須至少包含一個非空的 RequestURI (包含協議和 host)或非空的 Host 頭 + RequestURI。
客戶端以如下順序肯定待請求的服務端:
- 若是 RequestURI 包含完整的帶有協議和 host 的 url ,則從 RequestURI 中取得。
- 不然就從 Host 頭中取得。
這個函數不會跟隨重定向。若要跟隨重定向,請使用 Get*
。
若是 resp
是 nil
,那麼響應會被忽略。
若是向指定請求 host 的全部 DefaultMaxConnsPerHost
數量的鏈接都被佔用,那麼會返回 ErrNoFreeConns
。
在有性能要求的代碼中,推薦經過 AcquireRequest
和 AcquireResponse
來獲取 req
和 resp
。
func (*PipelineClient) DoTimeout
func (c *PipelineClient) DoTimeout(req *Request, resp *Response, timeout time.Duration) error
DoTimeout
發出指定的 http 請求,而且在指定的超時以前獲得響應後填充指定的 http 響應對象。
請求必須至少包含一個非空的 RequestURI (包含協議和 host)或非空的 Host 頭 + RequestURI。
客戶端以如下順序肯定待請求的服務端:
- 若是 RequestURI 包含完整的帶有協議和 host 的 url ,則從 RequestURI 中取得。
- 不然就從 Host 頭中取得。
這個函數不會跟隨重定向。若要跟隨重定向,請使用 Get*
。
若是 resp
是 nil
,那麼響應會被忽略。
若是向指定請求 host 的全部 DefaultMaxConnsPerHost
數量的鏈接都被佔用,那麼會返回 ErrNoFreeConns
。
在有性能要求的代碼中,推薦經過 AcquireRequest
和 AcquireResponse
來獲取 req
和 resp
。
func (*PipelineClient) PendingRequests
func (c *PipelineClient) PendingRequests() int
PendingRequests
返回正在執行的請求數。
type Request
type Request struct {
Header RequestHeader
}
Request
表明一個 HTTP 請求。
禁止拷貝 Request
實例。應該建立新實例或使用 CopyTo
。
Request
實例必須不能再多個運行的 goroutine 間使用。
func AcquireRequest
func AcquireRequest() *Request
AcquireRequest
從請求池中返回一個空的 Request
實例。
返回的 Request
實例在再也不須要時能夠經過 ReleaseRequest
釋放回池。這能夠下降垃圾回收負載。
func (*Request) AppendBody
func (req *Request) AppendBody(p []byte)
AppendBody
追加 p
至請求體。
在函數返回後重用 p
是安全的。
func (*Request) AppendBodyString