fasthttp 文檔手冊

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 // RFC 7231, 6.2.1
    StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2
    StatusProcessing         = 102 // RFC 2518, 10.1

    StatusOK                   = 200 // RFC 7231, 6.3.1
    StatusCreated              = 201 // RFC 7231, 6.3.2
    StatusAccepted             = 202 // RFC 7231, 6.3.3
    StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4
    StatusNoContent            = 204 // RFC 7231, 6.3.5
    StatusResetContent         = 205 // RFC 7231, 6.3.6
    StatusPartialContent       = 206 // RFC 7233, 4.1
    StatusMultiStatus          = 207 // RFC 4918, 11.1
    StatusAlreadyReported      = 208 // RFC 5842, 7.1
    StatusIMUsed               = 226 // RFC 3229, 10.4.1

    StatusMultipleChoices  = 300 // RFC 7231, 6.4.1
    StatusMovedPermanently = 301 // RFC 7231, 6.4.2
    StatusFound            = 302 // RFC 7231, 6.4.3
    StatusSeeOther         = 303 // RFC 7231, 6.4.4
    StatusNotModified      = 304 // RFC 7232, 4.1
    StatusUseProxy         = 305 // RFC 7231, 6.4.5

    StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7
    StatusPermanentRedirect = 308 // RFC 7538, 3

    StatusBadRequest                   = 400 // RFC 7231, 6.5.1
    StatusUnauthorized                 = 401 // RFC 7235, 3.1
    StatusPaymentRequired              = 402 // RFC 7231, 6.5.2
    StatusForbidden                    = 403 // RFC 7231, 6.5.3
    StatusNotFound                     = 404 // RFC 7231, 6.5.4
    StatusMethodNotAllowed             = 405 // RFC 7231, 6.5.5
    StatusNotAcceptable                = 406 // RFC 7231, 6.5.6
    StatusProxyAuthRequired            = 407 // RFC 7235, 3.2
    StatusRequestTimeout               = 408 // RFC 7231, 6.5.7
    StatusConflict                     = 409 // RFC 7231, 6.5.8
    StatusGone                         = 410 // RFC 7231, 6.5.9
    StatusLengthRequired               = 411 // RFC 7231, 6.5.10
    StatusPreconditionFailed           = 412 // RFC 7232, 4.2
    StatusRequestEntityTooLarge        = 413 // RFC 7231, 6.5.11
    StatusRequestURITooLong            = 414 // RFC 7231, 6.5.12
    StatusUnsupportedMediaType         = 415 // RFC 7231, 6.5.13
    StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4
    StatusExpectationFailed            = 417 // RFC 7231, 6.5.14
    StatusTeapot                       = 418 // RFC 7168, 2.3.3
    StatusUnprocessableEntity          = 422 // RFC 4918, 11.2
    StatusLocked                       = 423 // RFC 4918, 11.3
    StatusFailedDependency             = 424 // RFC 4918, 11.4
    StatusUpgradeRequired              = 426 // RFC 7231, 6.5.15
    StatusPreconditionRequired         = 428 // RFC 6585, 3
    StatusTooManyRequests              = 429 // RFC 6585, 4
    StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
    StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3

    StatusInternalServerError           = 500 // RFC 7231, 6.6.1
    StatusNotImplemented                = 501 // RFC 7231, 6.6.2
    StatusBadGateway                    = 502 // RFC 7231, 6.6.3
    StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
    StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
    StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.6.6
    StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
    StatusInsufficientStorage           = 507 // RFC 4918, 11.5
    StatusLoopDetected                  = 508 // RFC 5842, 7.2
    StatusNotExtended                   = 510 // RFC 2774, 7
    StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

與 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 在當特定的 host 沒有可用的鏈接時返回。//// 若是你看到了這個錯誤,你能夠選擇調高每一個 host 可用的鏈接數。
    ErrNoFreeConns = errors.New("no free connections available to host")

    // ErrTimeout 在調用超時時返回。
    ErrTimeout = errors.New("timeout")

    // ErrConnectionClosed 會在當服務端在返回第一個相應字節前被關閉時,// 於客戶端方法中返回。//// 若是你看到了這個錯誤,你能夠在服務端關閉鏈接前經過 `'Connection: close'` 相應頭// 來修復這個錯誤,或者在客戶端發送請求前添加 `'Connection: close'` 請求頭。
    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 能夠會被支持於 `Cookie.Expire` 中,用於爲指定// cookie 添加過時。
    CookieExpireDelete = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)

    // CookieExpireUnlimited 用於代表該 cookie 不會過時。
    CookieExpireUnlimited = zeroTime
)
var (
    // ErrPerIPConnLimit 會在任一 ip 鏈接數超過 Server.MaxConnsPerIP 時// 由 ServeConn 返回。
    ErrPerIPConnLimit = errors.New("too many connections per ip")

    // ErrConcurrencyLimit 會在併發鏈接數超過 Server.Concurrency 時由// ServeConn 返回。
    ErrConcurrencyLimit = errors.New("canot serve the connection because Server.Concurrency concurrent connections are served")

    // ErrKeepaliveTimeout 會在鏈接的時長超過 MaxKeepaliveDuration 時// 由 ServeConn 返回。
    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"// 當每一個請求到來時,這個函數都將被調用。// RequestCtx 提供了不少有用的處理 http 請求的方法。更多詳情請參閱 RequestCtx 說明。
requestHandler := func(ctx *fasthttp.RequestCtx) {
    fmt.Fprintf(ctx, "Hello, world! Requested path is %q", ctx.Path())
}

// 使用默認設置啓動服務器。// 建立服務器實例。//// ListenAndServe 只返回一個錯誤,因此它一般是永久阻塞的。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 都會一直保持阻塞。

例子:

// 建立一個接受請求的 listener//// 你不只能夠建立 TCP listener - 任意的 net.Listener 均可以。// 例如 UNIX Socket 或 TLS listener 。

ln, err := net.Listen("tcp4", "127.0.0.1:8080")
if err != nil {
    log.Fatalf("error in net.Listen: %s", err)
}

// 當每一個請求到來時,這個函數都將被調用。// RequestCtx 提供了不少有用的處理 http 請求的方法。更多詳情請參閱 RequestCtx 說明。
requestHandler := func(ctx *fasthttp.RequestCtx) {
    fmt.Fprintf(ctx, "Hello, world! Requested path is %q", ctx.Path())
}

// 使用默認設置啓動服務器。// 建立服務器實例。//// Serve 在 ln.Close() 或發生錯誤時返回,因此它一般是永久阻塞的。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 {

    // 客戶端名字。在 User-Agent 請求頭中會被使用到。//// 若是未被設置,則會使用默認客戶端名。
    Name string// 創建到指定 host 的新鏈接後的回調函數。//// 若是未被設置,則會使用默認 Dial 函數。
    Dial DialFunc

    // 若被設爲 true ,則會試圖鏈接 ipv4 和 ipv6 的地址。//// 這個選項僅在使用默認 TCP dialer 時有效,// 例如:Dial 爲空。//// 默認狀況下客戶端僅會鏈接 ipv4 地址,// 由於 ipv6 在世界上的大多數網絡中都仍然不可用 :)
    DialDualStack bool// HTTPS 鏈接的 TLS 配置。// 若是未被設置,則使用默認的 TLS 配置。
    TLSConfig *tls.Config

    // 每一個 host 能夠被創建的最大鏈接數。//// 若是未被設置,則使用默認的 DefaultMaxConnsPerHost 。
    MaxConnsPerHost int// 在這個時間間隔後,空閒的 keep-alive 鏈接會被關閉。// 默認值爲 DefaultMaxIdleConnDuration 。
    MaxIdleConnDuration time.Duration

    // 每一個鏈接響應讀取時的緩衝大小。// 這個值也限制了最大頭大小。//// 默認值爲 0 。
    ReadBufferSize int// 每一個鏈接請求寫入時的緩衝大小。//// 默認值爲 0 。
    WriteBufferSize int// 完整的響應讀取(包含響應體)可用的最大時間。//// 默認爲無限制。
    ReadTimeout time.Duration

    // 完整的請求寫入(包含請求體)可用的最大時間。//// 默認爲無限制。
    WriteTimeout time.Duration

    // 相應體的最大大小。//// 當該值大於 0 ,且相應體超過它時,客戶端返回 ErrBodyTooLarge 。// 默認爲無限制。
    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// 目錄中的索引文件名。//// 例子://// * index.html// * index.htm// * my-super-index.xml//// 默認爲空。
    IndexNames []string

    GenerateIndexPages bool// 若設爲 true ,則壓縮響應。//// 服務器會經過緩存來最小化 CPU 的使用。// 新的緩存文件名字會添加 `CompressedFileSuffix` 前綴。// 因此建議使服務器對 Root 目錄以及子目錄有寫權限。
    Compress bool// 若被設爲 true ,則啓用字節範圍請求//// 默認爲 false 。
    AcceptByteRange bool// 重寫路徑函數。//// 默認爲不改變請求路徑。
    PathRewrite PathRewriteFunc

    // 非活躍的文件句柄的過時時間間隔。//// 默認爲 `FSHandlerCacheDuration` 。
    CacheDuration time.Duration

    // 爲緩存的壓縮文件添加的前綴。//// 這個值僅在 Compress 被設置時纔有效。//// 默認爲 FSCompressedFileSuffix 。
    CompressedFileSuffix string// 包含被過濾或未導出的屬性
}

FS 表明了經過本地文件系統來響應靜態文件 HTTP 請求的設置。

不容許複製 FS 值,應該建立新的 FS 值。

例子:

fs := &fasthttp.FS{
    // 響應靜態文件請求的目錄
    Root: "/var/www/static-site",

    // 生成索引
    GenerateIndexPages: true,

    // 開啓壓縮,用於節省帶寬
    Compress: true,
}

// 建立響應靜態文件的 handler
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 {

    // 以逗號分隔的上游 HTTP 服務器 host 地址列表,經過輪詢傳遞給 Dial//// 若是默認的 dialer 被使用,每個地址都須要包含端口。// 例子://// - foobar.com:80// - foobar.com:443// - foobar.com:8080
    Addr string// 客戶端名,用於 User-Agent 請求頭。
    Name string// 創建到指定 host 的新鏈接後的回調函數。//// 若是未被設置,則會使用默認 Dial 函數。
    Dial DialFunc

    // 若被設爲 true ,則會試圖鏈接 ipv4 和 ipv6 的地址。//// 這個選項僅在使用默認 TCP dialer 時有效,// 例如:Dial 爲空。//// 默認狀況下客戶端僅會鏈接 ipv4 地址,// 由於 ipv6 在世界上的大多數網絡中都仍然不可用 :)
    DialDualStack bool// 是否使用 TLS 。
    IsTLS bool// 可選的 TLS 配置。
    TLSConfig *tls.Config

    // 每一個 host 能夠被創建的最大鏈接數。//// 若是未被設置,則使用默認的 DefaultMaxConnsPerHost 。
    MaxConns int// 在這個時間間隔後, keep-alive 鏈接會被關閉。// 默認值爲無限制。
    MaxConnDuration time.Duration

    // 在這個時間間隔後,空閒的 keep-alive 鏈接會被關閉。// 默認值爲 DefaultMaxIdleConnDuration 。
    MaxIdleConnDuration time.Duration

    // 每一個鏈接響應讀取時的緩衝大小。// 這個值也限制了最大頭大小。//// 默認值爲 0 。
    ReadBufferSize int// 每一個鏈接請求寫入時的緩衝大小。//// 默認值爲 0 。
    WriteBufferSize int// 完整的響應讀取(包含響應體)可用的最大時間。//// 默認爲無限制。
    ReadTimeout time.Duration

    // 完整的請求寫入(包含請求體)可用的最大時間。//// 默認爲無限制。
    WriteTimeout time.Duration

    // 相應體的最大大小。//// 當該值大於 0 ,且相應體超過它時,客戶端返回 ErrBodyTooLarge 。// 默認爲無限制。
    MaxResponseBodySize int

    DisableHeaderNamesNormalizing bool// 包含被過濾或未導出的屬性
}

HostClient 均衡地向列於 Addr 中的 host 發起請求。

禁止拷貝 HostClient 實例。應使用建立新的實例。

在多個運行的 goroutine 間執行 HostClient 方法是安全的。

例子:

package main

import (
    "log""github.com/valyala/fasthttp"
)

func main() {
    // 準備一個客戶端,用於經過監聽於 localhost:8080 的 HTTP 代理獲取網頁
    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)

    // 經過本地代理獲取 foobar 頁面。重用 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) {
  // 處理 body
}

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 必須與 log.Printf 有相同的語義。
    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 {

    // 鏈接的 host 的地址
    Addr string// 鏈接至 Addr 的最大併發數。//// 默認爲單鏈接。
    MaxConns int// 單個鏈接至 Addr 的最大等待管道請求數量。//// 默認爲 DefaultMaxPendingRequests 。
    MaxPendingRequests int// 在批量發送管道請求至服務器前的最大延時。//// 默認爲無延時。
    MaxBatchDelay time.Duration

    /// 創建到指定 host 的新鏈接後的回調函數。//// 若是未被設置,則會使用默認 Dial 函數。
    Dial DialFunc

    // 若被設爲 true ,則會試圖鏈接 ipv4 和 ipv6 的地址。//// 這個選項僅在使用默認 TCP dialer 時有效,// 例如:Dial 爲空。//// 默認狀況下客戶端僅會鏈接 ipv4 地址,// 由於 ipv6 在世界上的大多數網絡中都仍然不可用 :)
    DialDualStack bool// 是否使用 TLS 。
    IsTLS bool// 可選的 TLS 配置。
    TLSConfig *tls.Config

    // 在這個時間間隔後,空閒的 keep-alive 鏈接會被關閉。// 默認值爲 DefaultMaxIdleConnDuration 。
    MaxIdleConnDuration time.Duration

    // 每一個鏈接響應讀取時的緩衝大小。// 這個值也限制了最大頭大小。//// 默認值爲 0 。
    ReadBufferSize int// 每一個鏈接請求寫入時的緩衝大小。//// 默認值爲 0 。
    WriteBufferSize int// 完整的響應讀取(包含響應體)可用的最大時間。//// 默認爲無限制。
    ReadTimeout time.Duration

    // 完整的請求寫入(包含請求體)可用的最大時間。//// 默認爲無限制。
    WriteTimeout time.Duration

    // 用於記錄客戶端錯誤的日誌記錄器。//// 默認爲標準 log 庫。
    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 是禁止的。應使用指針。
    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


相關文章
相關標籤/搜索