fasthttp 文档手册

貌似文章有最大长度限制,完整全文地址:https://github.com/DavidCai1993/my-blog/issues/35

常量

  1. const (
  2. CompressNoCompression = flate.NoCompression
  3. CompressBestSpeed = flate.BestSpeed
  4. CompressBestCompression = flate.BestCompression
  5. CompressDefaultCompression = flate.DefaultCompression
  6. )

所支持的压缩级别。

  1. const (
  2. StatusContinue = 100 // RFC 7231, 6.2.1
  3. StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2
  4. StatusProcessing = 102 // RFC 2518, 10.1
  5. StatusOK = 200 // RFC 7231, 6.3.1
  6. StatusCreated = 201 // RFC 7231, 6.3.2
  7. StatusAccepted = 202 // RFC 7231, 6.3.3
  8. StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4
  9. StatusNoContent = 204 // RFC 7231, 6.3.5
  10. StatusResetContent = 205 // RFC 7231, 6.3.6
  11. StatusPartialContent = 206 // RFC 7233, 4.1
  12. StatusMultiStatus = 207 // RFC 4918, 11.1
  13. StatusAlreadyReported = 208 // RFC 5842, 7.1
  14. StatusIMUsed = 226 // RFC 3229, 10.4.1
  15. StatusMultipleChoices = 300 // RFC 7231, 6.4.1
  16. StatusMovedPermanently = 301 // RFC 7231, 6.4.2
  17. StatusFound = 302 // RFC 7231, 6.4.3
  18. StatusSeeOther = 303 // RFC 7231, 6.4.4
  19. StatusNotModified = 304 // RFC 7232, 4.1
  20. StatusUseProxy = 305 // RFC 7231, 6.4.5
  21. StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7
  22. StatusPermanentRedirect = 308 // RFC 7538, 3
  23. StatusBadRequest = 400 // RFC 7231, 6.5.1
  24. StatusUnauthorized = 401 // RFC 7235, 3.1
  25. StatusPaymentRequired = 402 // RFC 7231, 6.5.2
  26. StatusForbidden = 403 // RFC 7231, 6.5.3
  27. StatusNotFound = 404 // RFC 7231, 6.5.4
  28. StatusMethodNotAllowed = 405 // RFC 7231, 6.5.5
  29. StatusNotAcceptable = 406 // RFC 7231, 6.5.6
  30. StatusProxyAuthRequired = 407 // RFC 7235, 3.2
  31. StatusRequestTimeout = 408 // RFC 7231, 6.5.7
  32. StatusConflict = 409 // RFC 7231, 6.5.8
  33. StatusGone = 410 // RFC 7231, 6.5.9
  34. StatusLengthRequired = 411 // RFC 7231, 6.5.10
  35. StatusPreconditionFailed = 412 // RFC 7232, 4.2
  36. StatusRequestEntityTooLarge = 413 // RFC 7231, 6.5.11
  37. StatusRequestURITooLong = 414 // RFC 7231, 6.5.12
  38. StatusUnsupportedMediaType = 415 // RFC 7231, 6.5.13
  39. StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4
  40. StatusExpectationFailed = 417 // RFC 7231, 6.5.14
  41. StatusTeapot = 418 // RFC 7168, 2.3.3
  42. StatusUnprocessableEntity = 422 // RFC 4918, 11.2
  43. StatusLocked = 423 // RFC 4918, 11.3
  44. StatusFailedDependency = 424 // RFC 4918, 11.4
  45. StatusUpgradeRequired = 426 // RFC 7231, 6.5.15
  46. StatusPreconditionRequired = 428 // RFC 6585, 3
  47. StatusTooManyRequests = 429 // RFC 6585, 4
  48. StatusRequestHeaderFieldsTooLarge = 431 // RFC 6585, 5
  49. StatusUnavailableForLegalReasons = 451 // RFC 7725, 3
  50. StatusInternalServerError = 500 // RFC 7231, 6.6.1
  51. StatusNotImplemented = 501 // RFC 7231, 6.6.2
  52. StatusBadGateway = 502 // RFC 7231, 6.6.3
  53. StatusServiceUnavailable = 503 // RFC 7231, 6.6.4
  54. StatusGatewayTimeout = 504 // RFC 7231, 6.6.5
  55. StatusHTTPVersionNotSupported = 505 // RFC 7231, 6.6.6
  56. StatusVariantAlsoNegotiates = 506 // RFC 2295, 8.1
  57. StatusInsufficientStorage = 507 // RFC 4918, 11.5
  58. StatusLoopDetected = 508 // RFC 5842, 7.2
  59. StatusNotExtended = 510 // RFC 2774, 7
  60. StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
  61. )

与 net/http 相同的 HTTP 状态吗。

  1. const DefaultConcurrency = 256 * 1024

DefaultConcurrency 为默认情况下(没有设置 Server.Concurrency 时)服务器可以接受的最大并发请求数。

  1. const DefaultDNSCacheDuration = time.Minute

DefaultDNSCacheDuration 是由 Dial* 函数族缓存处理过的 TCP 地址的持续时间。

  1. const DefaultDialTimeout = 3 * time.Second

DefaultDialTimeout 是由 Dial 和 DialDualStack 使用的用于建立 TCP 连接的超时时间。

  1. const DefaultMaxConnsPerHost = 512

DefaultMaxConnsPerHost 是 http 客户端在默认情况下(如果没有设置 Client.MaxConnsPerHost)单个 host 可以建立的最大并发连接数。

  1. const DefaultMaxIdleConnDuration = 10 * time.Second

DefaultMaxIdleConnDuration 是在空闲的 keep-alive 连接被关闭前默认的持续时间。

  1. const DefaultMaxPendingRequests = 1024

DefaultMaxPendingRequests 是 PipelineClient.MaxPendingRequests 的默认值。

  1. const DefaultMaxRequestBodySize = 4 * 1024 * 1024

DefaultMaxRequestBodySize 是服务器默认可读的最大请求体大小。

更多详情请参阅 Server.MaxRequestBodySize 。

  1. const FSCompressedFileSuffix = ".fasthttp.gz"

FSCompressedFileSuffix 是当需要使用新文件名存储被压缩后的文件时, FS 在原始文件名上添加的前缀。更多详情请参阅 FS.Compress 。

  1. const FSHandlerCacheDuration = 10 * time.Second

FSHandlerCacheDuration 是由 FS 所打开的非活跃文件句柄的默认失效时间。

变量

  1. var (
  2. // ErrNoFreeConns 在当特定的 host 没有可用的连接时返回。//// 如果你看到了这个错误,你可以选择调高每个 host 可用的连接数。
  3. ErrNoFreeConns = errors.New("no free connections available to host")
  4. // ErrTimeout 在调用超时时返回。
  5. ErrTimeout = errors.New("timeout")
  6. // ErrConnectionClosed 会在当服务端在返回第一个相应字节前被关闭时,// 于客户端方法中返回。//// 如果你看到了这个错误,你可以在服务端关闭连接前通过 `'Connection: close'` 相应头// 来修复这个错误,或者在客户端发送请求前添加 `'Connection: close'` 请求头。
  7. ErrConnectionClosed = errors.New("the server closed connection before returning the first response byte. " +
  8. "Make sure the server returns 'Connection: close' response header before closing the connection")
  9. )
  1. var (
  2. // CookieExpireDelete 可以会被支持于 `Cookie.Expire` 中,用于为指定// cookie 添加过期。
  3. CookieExpireDelete = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
  4. // CookieExpireUnlimited 用于表明该 cookie 不会过期。
  5. CookieExpireUnlimited = zeroTime
  6. )
  1. var (
  2. // ErrPerIPConnLimit 会在任一 ip 连接数超过 Server.MaxConnsPerIP 时// 由 ServeConn 返回。
  3. ErrPerIPConnLimit = errors.New("too many connections per ip")
  4. // ErrConcurrencyLimit 会在并发连接数超过 Server.Concurrency 时由// ServeConn 返回。
  5. ErrConcurrencyLimit = errors.New("canot serve the connection because Server.Concurrency concurrent connections are served")
  6. // ErrKeepaliveTimeout 会在连接的时长超过 MaxKeepaliveDuration 时// 由 ServeConn 返回。
  7. ErrKeepaliveTimeout = errors.New("exceeded MaxKeepaliveDuration")
  8. )
  1. var ErrBodyTooLarge = errors.New("body size exceeds the given limit")

ErrBodyTooLarge 会在请求体或者响应体超过指定限制时返回。

  1. var ErrDialTimeout = errors.New("dialing to the given TCP address timed out")

ErrDialTimeout 会在 TCP 握手超时时触发。

  1. var ErrMissingFile = errors.New("there is no uploaded file associated with the given key")

ErrMissingFile 会在没有与指定的 multipart 表单键相关联的被上传文件时由 FormFile 返回。

  1. var ErrNoArgValue = errors.New("no Args value for the given key")

ErrNoArgValue 会在指定 Args 键缺少值时返回。

  1. var ErrNoMultipartForm = errors.New("request has no multipart/form-data Content-Type")

ErrNoMultipartForm 意味着请求的 Content-Type 不是 'multipart/form-data' 。

  1. var ErrPipelineOverflow = errors.New("pipelined requests' queue has been overflown. Increase MaxConns and/or MaxPendingRequests")

ErrPipelineOverflow 会在请求的队列溢出时,由 PipelineClient.Do* 函数族返回。

func AppendBytesStr

  1. func AppendBytesStr(dst []byte, src string) []byte

AppendBytesStr 向 dst 追加 src ,并且返回追加后的 dst 。

这个函数与 append(dst, src...) 的性能没有差别。目前它仅用于向后兼容。

这个函数已经弃用并且可能很快被移除。

func AppendGunzipBytes

  1. func AppendGunzipBytes(dst, src []byte) ([]byte, error)

AppendGunzipBytes 向 dst 追加 gunzip 压缩后的 src ,并且返回追加后的 dst 。

func AppendGzipBytes

  1. func AppendGzipBytes(dst, src []byte) []byte

AppendGzipBytes 向 dst 追加 gzip 压缩后的 src ,并且返回追加后的 dst 。

func AppendGzipBytesLevel

  1. func AppendGzipBytesLevel(dst, src []byte, level int) []byte

AppendGzipBytesLevel 向 dst 追加指定级别的 gzip 压缩后的 src ,并且返回追加后的 dst 。

支持的压缩级别有:

  • CompressNoCompression
  • CompressBestSpeed
  • CompressBestCompression
  • CompressDefaultCompression

func AppendHTMLEscape

  1. func AppendHTMLEscape(dst []byte, s string) []byte

AppendHTMLEscape 向 dst 追加 HTML 转义后的 src ,并且返回追加后的 dst 。

func AppendHTMLEscapeBytes

  1. func AppendHTMLEscapeBytes(dst, s []byte) []byte

AppendHTMLEscapeBytes 向 dst 追加 HTML 转义后的 src ,并且返回追加后的 dst 。

func AppendHTTPDate

  1. func AppendHTTPDate(dst []byte, date time.Time) []byte

AppendHTTPDate 向 dst 追加符合 HTTP-compliant (RFC1123) 表示的时间 ,并且返回追加后的 dst 。

func AppendIPv4

  1. func AppendIPv4(dst []byte, ip net.IP) []byte

AppendIPv4 向 dst 追加表示 ip v4 的字符串 ,并且返回追加后的 dst 。

func AppendNormalizedHeaderKey

  1. 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

  1. func AppendNormalizedHeaderKeyBytes(dst, key []byte) []byte

AppendNormalizedHeaderKeyBytes 向 dst 追加标准化后的 HTTP 头键(名),并且返回追加后的 dst 。

标准化后的头键由一个大写字母开头。在 - 后的第一个字母也为大写。其他的所有字母则都为小写。例子:

  • coNTENT-TYPe -> Content-Type
  • HOST -> Host
  • foo-bar-baz -> Foo-Bar-Baz

func AppendQuotedArg

  1. func AppendQuotedArg(dst, src []byte) []byte

AppendQuotedArg 向 dst 追加经过 url 加密的 src ,并且返回追加后的 dst 。

func AppendUint

  1. func AppendUint(dst []byte, n int) []byte

AppendUint 向 dst 追加 n,并且返回追加后的 dst 。

func Dial

  1. 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

  1. 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

  1. 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

  1. 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

  1. 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

  1. 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

  1. 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

  1. func EqualBytesStr(b []byte, s string) bool

EqualBytesStr,在 string(b) == s 时返回 true

这个函数与 string(b) == s 的性能没有差别。目前它仅用于向后兼容。

这个函数已经弃用并且可能很快被移除。

func FileLastModified

  1. func FileLastModified(path string) (time.Time, error)

FileLastModified 返回文件的最后修改时间。

func Get

  1. func Get(dst []byte, url string) (statusCode int, body []byte, err error)

Get 向 dst 追加 url 信息,并且通过 body 返回它。

这个函数会跟随重定向。若要手动操作重定向,请使用 Do* 。

如果 dst 为 nil ,那么则会分配一个新的 body 缓冲。

func GetDeadline

  1. 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

  1. 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

  1. func ListenAndServe(addr string, handler RequestHandler) error

ListenAndServe 使用指定的 handler 处理来自指定 TCP 地址 addr 的 HTTP 请求。

例子:

  1. // 这个服务器会监听所有来自该地址的请求
  2. listenAddr := "127.0.0.1:80"// 当每个请求到来时,这个函数都将被调用。// RequestCtx 提供了很多有用的处理 http 请求的方法。更多详情请参阅 RequestCtx 说明。
  3. requestHandler := func(ctx *fasthttp.RequestCtx) {
  4. fmt.Fprintf(ctx, "Hello, world! Requested path is %q", ctx.Path())
  5. }
  6. // 使用默认设置启动服务器。// 创建服务器实例。//// ListenAndServe 只返回一个错误,所以它通常是永久阻塞的。if err := fasthttp.ListenAndServe(listenAddr, requestHandler); err != nil {
  7. log.Fatalf("error in ListenAndServe: %s", err)
  8. }

func ListenAndServeTLS

  1. func ListenAndServeTLS(addr, certFile, keyFile string, handler RequestHandler) error

ListenAndServeTLS 使用指定的 handler 处理来自指定 TCP 地址 addr 的 HTTPS 请求。

certFile 和 keyFile 是 TLS 证书和密钥文件的路径。

func ListenAndServeTLSEmbed

  1. func ListenAndServeTLSEmbed(addr string, certData, keyData []byte, handler RequestHandler) error

ListenAndServeTLSEmbed 使用指定的 handler 处理来自指定 TCP 地址 addr 的 HTTPS 请求。

certData 和 keyData 必须包含合法的 TLS 证书和密钥数据。

func ListenAndServeUNIX

  1. func ListenAndServeUNIX(addr string, mode os.FileMode, handler RequestHandler) error

ListenAndServeUNIX 使用指定的 handler 处理来自指定 UNIX 地址 addr 的 HTTP 请求。

这个函数会在开始接受请求前删除所有 addr 下的文件。

该函数会为制定 UNIX 地址 addr 设置参数中指定的 mode 。

func NewStreamReader

  1. func NewStreamReader(sw StreamWriter) io.ReadCloser

NewStreamReader 返回一个 reader ,用于获取所有由 sw 生成的数据。

返回的 reader 可以被传递至 Response.SetBodyStream 。

在返回的 reader 中所有的数据都被读取完毕之后,必须调用 Close 。否则可能会造成 goroutine 泄露。

更多详情可参阅 Response.SetBodyStreamWriter 。

func ParseByteRange

  1. 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

  1. func ParseHTTPDate(date []byte) (time.Time, error)

ParseHTTPDate 用于解释符合 HTTP-compliant (RFC1123) 规范的时间。

func ParseIPv4

  1. func ParseIPv4(dst net.IP, ipStr []byte) (net.IP, error)

ParseIPv4 解释 ipStr 提供的 ip 地址,并填充 dst ,然后返回填充后的 dst 。

func ParseUfloat

  1. func ParseUfloat(buf []byte) (float64, error)

ParseUfloat 解释 buf 提供的无符号浮点数。

func ParseUint

  1. func ParseUint(buf []byte) (int, error)

ParseUint 解释 buf 提供的无符号整型数。

func Post

  1. 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

  1. func ReleaseArgs(a *Args)

ReleaseArgs 向池中释放通过 AquireArgs 取得的对象。

不要试图访问释放的 Args 对象,可能会产生数据竞争。

func ReleaseByteBuffer

  1. func ReleaseByteBuffer(b *ByteBuffer)

ReleaseByteBuffer 返回池中释放指定字节缓冲。

在释放回池之后, ByteBuffer.B 不能再被访问,可能会产生数据竞争。

func ReleaseCookie

  1. func ReleaseCookie(c *Cookie)

ReleaseCookie 向池中释放由 AcquireCookie 返回的对象。

不要试图访问释放的 Cookie 对象,可能会产生数据竞争。

func ReleaseRequest

  1. func ReleaseRequest(req *Request)

ReleaseRequest 向池中释放由 AcquireRequest 返回的对象。

在释放回池之后,禁止再访问 req 对象以及它的任何成员。

func ReleaseResponse

  1. func ReleaseResponse(resp *Response)

ReleaseResponse 向池中释放由 AcquireResponse 返回的对象。

在释放回池之后,禁止再访问 resp 对象以及它的任何成员。

func ReleaseURI

  1. func ReleaseURI(u *URI)

ReleaseURI 向池中释放由 AcquireURI 返回的对象。

不要试图访问释放的 URI 对象,可能会产生数据竞争。

func SaveMultipartFile

  1. func SaveMultipartFile(fh *multipart.FileHeader, path string) error

SaveMultipartFile 在指定的 path 下保存文件 fh 。

func Serve

  1. func Serve(ln net.Listener, handler RequestHandler) error

Serve 使用指定的 handler 来处理来自 listener 的连接。

在 listener 返回永久性的错误之前, Serve 都会一直保持阻塞。

例子:

  1. // 创建一个接受请求的 listener//// 你不仅可以创建 TCP listener - 任意的 net.Listener 都可以。// 例如 UNIX Socket 或 TLS listener 。
  2. ln, err := net.Listen("tcp4", "127.0.0.1:8080")
  3. if err != nil {
  4. log.Fatalf("error in net.Listen: %s", err)
  5. }
  6. // 当每个请求到来时,这个函数都将被调用。// RequestCtx 提供了很多有用的处理 http 请求的方法。更多详情请参阅 RequestCtx 说明。
  7. requestHandler := func(ctx *fasthttp.RequestCtx) {
  8. fmt.Fprintf(ctx, "Hello, world! Requested path is %q", ctx.Path())
  9. }
  10. // 使用默认设置启动服务器。// 创建服务器实例。//// Serve 在 ln.Close() 或发生错误时返回,所以它通常是永久阻塞的。if err := fasthttp.Serve(ln, requestHandler); err != nil {
  11. log.Fatalf("error in Serve: %s", err)
  12. }

func ServeConn

  1. func ServeConn(c net.Conn, handler RequestHandler) error

ServeConn 使用指定的 handler 处理来自指定连接的 HTTP 请求。

如果所有来自 c 的请求都被成功处理,ServeConn 会返回 nil 。否则返回一个非空错误。

连接 c 必须立刻将所有数据通过 Write() 发送至客户端,否则请求的处理可能会被挂起。

ServeConn 在返回之前会关闭 c 。

func ServeFile

  1. func ServeFile(ctx *RequestCtx, path string)

ServeFile 返回来自指定 path 的压缩后文件内容的 HTTP 响应。

在以下情况下,HTTP 响应可能会包含未压缩文件内容:

  • 缺少 'Accept-Encoding: gzip' 请求头。
  • 没有对文件目录的写权限。

如果 path 指向一个目录,那么目录的内容会被返回。

如果你不需要响应压缩后的文件内容,请使用 ServeFileUncompressed 。

更多详情可参阅 RequestCtx.SendFile 。

func ServeFileBytes

  1. func ServeFileBytes(ctx *RequestCtx, path []byte)

ServeFileBytes 返回来自指定 path 的压缩后文件内容的 HTTP 响应。

在以下情况下,HTTP 响应可能会包含未压缩文件内容:

  • 缺少 'Accept-Encoding: gzip' 请求头。
  • 没有对文件目录的写权限。

如果 path 指向一个目录,那么目录的内容会被返回。

如果你不需要响应压缩后的文件内容,请使用 ServeFileUncompressed 。

更多详情可参阅 RequestCtx.SendFile 。

func ServeFileBytesUncompressed

  1. func ServeFileBytesUncompressed(ctx *RequestCtx, path []byte)

ServeFileBytesUncompressed 返回来自指定 path 文件内容的 HTTP 响应。

如果 path 指向一个目录,那么目录的内容会被返回。

若需要处理压缩后的文件,请使用 ServeFileBytes 。

更多详情可参阅 RequestCtx.SendFileBytes 。

func ServeFileUncompressed

  1. func ServeFileUncompressed(ctx *RequestCtx, path string)

ServeFileUncompressed 返回来自指定 path 文件内容的 HTTP 响应。

如果 path 指向一个目录,那么目录的内容会被返回。

若需要处理压缩后的文件,请使用 ServeFile 。

更多详情可参阅 RequestCtx.SendFile 。

func ServeTLS

  1. func ServeTLS(ln net.Listener, certFile, keyFile string, handler RequestHandler) error

ServeTLS 使用指定的 handler 来处理来自指定 net.Listener 的 HTTPS 请求。

certFile 和 keyFile 是 TLS 证书和密钥文件的路径。

func ServeTLSEmbed

  1. func ServeTLSEmbed(ln net.Listener, certData, keyData []byte, handler RequestHandler) error

ServeTLSEmbed 使用指定的 handler 来处理来自指定 net.Listener 的 HTTPS 请求。

certData 和 keyData 必须包含合法的 TLS 证书和密钥数据。

func StatusMessage

  1. func StatusMessage(statusCode int) string

StatusMessage 根据指定的状态码返回 HTTP 状态信息。

func WriteGunzip

  1. func WriteGunzip(w io.Writer, p []byte) (int, error)

WriteGunzip 向 w 写入经 gunzip 压缩的 p ,并且返回未压缩的字节数。

func WriteGzip

  1. func WriteGzip(w io.Writer, p []byte) (int, error)

WriteGunzip 向 w 写入经 gzip 压缩的 p ,并且返回未压缩的字节数。

func WriteGzipLevel

  1. func WriteGzipLevel(w io.Writer, p []byte, level int) (int, error)

WriteGunzip 向 w 写入经指定级别 gzip 压缩的 p ,并且返回未压缩的字节数。

支持的压缩级别有:

  • CompressNoCompression
  • CompressBestSpeed
  • CompressBestCompression
  • CompressDefaultCompression

func WriteInflate

  1. func WriteInflate(w io.Writer, p []byte) (int, error)

WriteGunzip 向 w 写入压缩后的 p ,并且返回未压缩的字节数。

func WriteMultipartForm

  1. func WriteMultipartForm(w io.Writer, f *multipart.Form, boundary string) error

WriteMultipartForm 使用指定的 w 写入指定的表单 f 。

type Args

  1. type Args struct {
  2. // 包含被过滤或未导出的属性
  3. }

Args 代表查询字符串参数。

拷贝 Args 实例是禁止的。你需要使用 CopyTo() 函数或创建一个新实例。

Args 实例必须不能在并发执行的 goroutine 间使用。

func AcquireArgs

  1. func AcquireArgs() *Args

AcquireArgs 从池中返回一个空的 Args 对象。

返回的 Args 实例在不再需要时可以通过 ReleaseArgs 释放回池。这可以降低垃圾回收负载。

func (*Args) Add

  1. func (a *Args) Add(key, value string)

Add 添加 'key=value' 参数。

同一个 key 可以添加多个值。

func (*Args) AddBytesK

  1. func (a *Args) AddBytesK(key []byte, value string)

AddBytesK 添加 'key=value' 参数。

同一个 key 可以添加多个值。

func (*Args) AddBytesKV

  1. func (a *Args) AddBytesKV(key, value []byte)

AddBytesKV 添加 'key=value' 参数。

同一个 key 可以添加多个值。

func (*Args) AddBytesV

  1. func (a *Args) AddBytesV(key string, value []byte)

AddBytesV 添加 'key=value' 参数。

同一个 key 可以添加多个值。

func (*Args) AppendBytes

  1. func (a *Args) AppendBytes(dst []byte) []byte

AppendBytes 像 dst 追加查询字符串,并返回 dst 。

func (*Args) CopyTo

  1. func (a *Args) CopyTo(dst *Args)

CopyTo 将所有的参数复制至 dst 。

func (*Args) Del

  1. func (a *Args) Del(key string)

Del 删除键为指定 key 的参数。

func (*Args) DelBytes

  1. func (a *Args) DelBytes(key []byte)

Del 删除键为指定 key 的参数。

func (*Args) GetUfloat

  1. func (a *Args) GetUfloat(key string) (float64, error)

GetUfloat 返回指定 key 的无符号浮点数值。

func (*Args) GetUfloatOrZero

  1. func (a *Args) GetUfloatOrZero(key string) float64

GetUfloatOrZero 返回指定 key 的无符号浮点数值。

当出错时返回 0 。

func (*Args) GetUint

  1. func (a *Args) GetUint(key string) (int, error)

GetUint 返回指定 key 的无符号整型数值。

func (*Args) GetUintOrZero

  1. func (a *Args) GetUintOrZero(key string) int

GetUintOrZero 返回指定 key 的无符号整型数值。

当出错时返回 0 。

func (*Args) Has

  1. func (a *Args) Has(key string) bool

Has 在当 Args 中存在指定 key 时返回 true 。

func (*Args) HasBytes

  1. func (a *Args) HasBytes(key []byte) bool

HasBytes 在当 Args 中存在指定 key 时返回 true 。

func (*Args) Len

  1. func (a *Args) Len() int

Len 查询参数的数量。

func (*Args) Parse

  1. func (a *Args) Parse(s string)

Parse 解析包含查询参数的字符串。

func (*Args) ParseBytes

  1. func (a *Args) ParseBytes(b []byte)

ParseBytes 解析包含查询参数的 b

func (*Args) Peek

  1. func (a *Args) Peek(key string) []byte

Peek 返回查询参数中指定 key 的值。

func (*Args) PeekBytes

  1. func (a *Args) PeekBytes(key []byte) []byte

PeekBytes 返回查询参数中指定 key 的值。

func (*Args) PeekMulti

  1. func (a *Args) PeekMulti(key string) [][]byte

PeekMulti 返回查询参数中指定 key 的所有值。

func (*Args) PeekMultiBytes

  1. func (a *Args) PeekMultiBytes(key []byte) [][]byte

PeekMultiBytes 返回查询参数中指定 key 的所有值。

func (*Args) QueryString

  1. func (a *Args) QueryString() []byte

QueryString 返回查询参数的字符串表示。

在下个 Args 方法调用之前,返回值都是合法的。

func (*Args) Reset

  1. func (a *Args) Reset()

Reset 清除所有查询参数。

func (*Args) Set

  1. func (a *Args) Set(key, value string)

Set 设置 'key=value' 参数。

func (*Args) SetBytesK

  1. func (a *Args) SetBytesK(key []byte, value string)

SetBytesK 设置 'key=value' 参数。

func (*Args) SetBytesKV

  1. func (a *Args) SetBytesKV(key, value []byte)

SetBytesKV 设置 'key=value' 参数。

func (*Args) SetBytesV

  1. func (a *Args) SetBytesV(key string, value []byte)

SetBytesV 设置 'key=value' 参数。

func (*Args) SetUint

  1. func (a *Args) SetUint(key string, value int)

SetUint 为指定 key 设置无符号整数值。

func (*Args) SetUintBytes

  1. func (a *Args) SetUintBytes(key []byte, value int)

SetUintBytes 为指定 key 设置无符号整数值。

func (*Args) String

  1. func (a *Args) String() string

String 返回查询参数的字符串表示。

func (*Args) VisitAll

  1. func (a *Args) VisitAll(f func(key, value []byte))

VisitAll 对每一个存在的参数调用 f 。

f 在返回后必须不能保留对键和值的引用。若要在返回后扔需要存储它们,请存储它们的副本。

func (*Args) WriteTo

  1. func (a *Args) WriteTo(w io.Writer) (int64, error)

WriteTo 向 w 写入查询字符串。

WriteTo 实现了 io.WriterTo 接口。

type Client

  1. type Client struct {
  2. // 客户端名字。在 User-Agent 请求头中会被使用到。//// 如果未被设置,则会使用默认客户端名。
  3. Name string// 建立到指定 host 的新连接后的回调函数。//// 如果未被设置,则会使用默认 Dial 函数。
  4. Dial DialFunc
  5. // 若被设为 true ,则会试图连接 ipv4 和 ipv6 的地址。//// 这个选项仅在使用默认 TCP dialer 时有效,// 例如:Dial 为空。//// 默认情况下客户端仅会连接 ipv4 地址,// 因为 ipv6 在世界上的大多数网络中都仍然不可用 :)
  6. DialDualStack bool// HTTPS 连接的 TLS 配置。// 如果未被设置,则使用默认的 TLS 配置。
  7. TLSConfig *tls.Config
  8. // 每个 host 可以被建立的最大连接数。//// 如果未被设置,则使用默认的 DefaultMaxConnsPerHost 。
  9. MaxConnsPerHost int// 在这个时间间隔后,空闲的 keep-alive 连接会被关闭。// 默认值为 DefaultMaxIdleConnDuration 。
  10. MaxIdleConnDuration time.Duration
  11. // 每个连接响应读取时的缓冲大小。// 这个值也限制了最大头大小。//// 默认值为 0 。
  12. ReadBufferSize int// 每个连接请求写入时的缓冲大小。//// 默认值为 0 。
  13. WriteBufferSize int// 完整的响应读取(包含响应体)可用的最大时间。//// 默认为无限制。
  14. ReadTimeout time.Duration
  15. // 完整的请求写入(包含请求体)可用的最大时间。//// 默认为无限制。
  16. WriteTimeout time.Duration
  17. // 相应体的最大大小。//// 当该值大于 0 ,且相应体超过它时,客户端返回 ErrBodyTooLarge 。// 默认为无限制。
  18. MaxResponseBodySize int
  19. DisableHeaderNamesNormalizing bool// 包含被过滤或未导出的属性
  20. }

Client 实现了 HTTP 客户端。

不允许按值拷贝 Client ,应该创建一个新的实例。

在多个运行的 goroutine 间调用 Client 方法是安全的。

func (*Client) Do

  1. 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

  1. 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

  1. 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

  1. 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

  1. 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

  1. 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

  1. 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

  1. type Cookie struct {
  2. // 包含被过滤或未导出的属性
  3. }

Cookie 代表 HTTP 相应的 cookie 。

不允许按值拷贝 Cookie ,应该创建一个新的实例。

在多个运行的 goroutine 间使用 Cookie 实例是禁止的。

func AcquireCookie

  1. func AcquireCookie() *Cookie

AcquireCookie 从池中返回一个空的 Cookie 对象。

返回的 Cookie 实例在不再需要时可以通过 ReleaseCookie 释放回池。这可以降低垃圾回收负载。

func (*Cookie) AppendBytes

  1. func (c *Cookie) AppendBytes(dst []byte) []byte

AppendBytes 向 dst 追加 cookie ,并且返回追加后的 dst 。

func (*Cookie) Cookie

  1. func (c *Cookie) Cookie() []byte

Cookie 返回 cookie 的表示。

直到下次调用 Cookie 方法前,返回值都是合法的。

func (*Cookie) CopyTo

  1. func (c *Cookie) CopyTo(src *Cookie)

CopyTo 拷贝 src cookie 至 c 。

func (*Cookie) Domain

  1. func (c *Cookie) Domain() []byte

Domain 返回 cookie 的 domain 值。

直到下次调用会改变 Cookie 的方法前,返回值都是合法的。

func (*Cookie) Expire

  1. func (c *Cookie) Expire() time.Time

Expire 返回 cookie 的过期时间。

若没设置过期,则返回 CookieExpireUnlimited 。

func (*Cookie) HTTPOnly

  1. func (c *Cookie) HTTPOnly() bool

HTTPOnly 在 cookie 为 http only 时返回 true 。

func (*Cookie) Key

  1. func (c *Cookie) Key() []byte

Key 返回 cookie 名字。

直到下次调用会改变 Cookie 的方法前,返回值都是合法的。

func (*Cookie) Parse

  1. func (c *Cookie) Parse(src string) error

Parse 解析 Set-Cookie 头。

func (*Cookie) ParseBytes

  1. func (c *Cookie) ParseBytes(src []byte) error

ParseBytes 解析 Set-Cookie 头。

func (*Cookie) Path

  1. func (c *Cookie) Path() []byte

Path 返回 cookie path 。

func (*Cookie) Reset

  1. func (c *Cookie) Reset()

Reset 清空该 cookie 。

func (*Cookie) Secure

  1. func (c *Cookie) Secure() bool

Secure 在当 cookie 为 secure 时返回 true 。

func (*Cookie) SetDomain

  1. func (c *Cookie) SetDomain(domain string)

SetDomain 设置 cookie 的 domain 。

func (*Cookie) SetDomainBytes

  1. func (c *Cookie) SetDomainBytes(domain []byte)

SetDomainBytes 设置 cookie 的 domain 。

func (*Cookie) SetExpire

  1. func (c *Cookie) SetExpire(expire time.Time)

SetExpire 设置 cookie 的过期时间。

若要使该 cookie 在客户端过期,则将值设置为 CookieExpireDelete 。

默认情况下 cookie 的寿命由浏览器会话限制。

func (*Cookie) SetHTTPOnly

  1. func (c *Cookie) SetHTTPOnly(httpOnly bool)

SetHTTPOnly 将 cookie 的 httpOnly 标识设置为指定值。

func (*Cookie) SetKey

  1. func (c *Cookie) SetKey(key string)

SetKey 设置 cookie 名。

func (*Cookie) SetKeyBytes

  1. func (c *Cookie) SetKeyBytes(key []byte)

SetKeyBytes 设置 cookie 名。

func (*Cookie) SetPath

  1. func (c *Cookie) SetPath(path string)

SetPath 设置 cookie 路径。

func (*Cookie) SetPathBytes

  1. func (c *Cookie) SetPathBytes(path []byte)

SetPathBytes 设置 cookie 路径。

func (*Cookie) SetSecure

  1. func (c *Cookie) SetSecure(secure bool)

SetSecure 将 cookie 的 secure 标识设置为指定值。

func (*Cookie) SetValue

  1. func (c *Cookie) SetValue(value string)

SetValue 设置 cookie 的值。

func (*Cookie) SetValueBytes

  1. func (c *Cookie) SetValueBytes(value []byte)

SetValueBytes 设置 cookie 的值。

func (*Cookie) String

  1. func (c *Cookie) String() string

String 返回 cookie 的字符串表示。

func (*Cookie) Value

  1. func (c *Cookie) Value() []byte

Value 返回 cookie 的值。

直到下次调用会改变 Cookie 的方法前,返回值都是合法的。

func (*Cookie) WriteTo

  1. func (c *Cookie) WriteTo(w io.Writer) (int64, error)

WriteTo 将 cookie 的字符串表示写入 w 。

WriteTo 实现了 io.WriterTo 接口。

type DialFunc

  1. 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

  1. type FS struct {
  2. // 用于响应文件的根目录
  3. Root string// 目录中的索引文件名。//// 例子://// * index.html// * index.htm// * my-super-index.xml//// 默认为空。
  4. IndexNames []string
  5. GenerateIndexPages bool// 若设为 true ,则压缩响应。//// 服务器会通过缓存来最小化 CPU 的使用。// 新的缓存文件名字会添加 `CompressedFileSuffix` 前缀。// 所以建议使服务器对 Root 目录以及子目录有写权限。
  6. Compress bool// 若被设为 true ,则启用字节范围请求//// 默认为 false 。
  7. AcceptByteRange bool// 重写路径函数。//// 默认为不改变请求路径。
  8. PathRewrite PathRewriteFunc
  9. // 非活跃的文件句柄的过期时间间隔。//// 默认为 `FSHandlerCacheDuration` 。
  10. CacheDuration time.Duration
  11. // 为缓存的压缩文件添加的前缀。//// 这个值仅在 Compress 被设置时才有效。//// 默认为 FSCompressedFileSuffix 。
  12. CompressedFileSuffix string// 包含被过滤或未导出的属性
  13. }

FS 代表了通过本地文件系统来响应静态文件 HTTP 请求的设置。

不允许复制 FS 值,应该创建新的 FS 值。

例子:

  1. fs := &fasthttp.FS{
  2. // 响应静态文件请求的目录
  3. Root: "/var/www/static-site",
  4. // 生成索引
  5. GenerateIndexPages: true,
  6. // 开启压缩,用于节省带宽
  7. Compress: true,
  8. }
  9. // 创建响应静态文件的 handler
  10. h := fs.NewRequestHandler()
  11. // 启动服务器if err := fasthttp.ListenAndServe(":8080", h); err != nil {
  12. log.Fatalf("error in ListenAndServe: %s", err)
  13. }

func (*FS) NewRequestHandler

  1. func (fs *FS) NewRequestHandler() RequestHandler

NewRequestHandler 通过指定的 FS 设置返回新的请求 handler 。

返回的 handler 根据 FS.CacheDuration 来缓存请求的文件句柄。若 FS.Root 目录包含大量文件,请确保你的程序通过 'ulimit -n' 来保证有足够的“可打开文件”。

不需要对单个 FS 实例创建多个请求 handler ,只需重用即可。

type HijackHandler

  1. type HijackHandler func(c net.Conn)

HijackHandler 必须处理拦截的连接 c 。

在 HijackHandler 返回后连接 c 会被自动关闭。

在 HijackHandler 返回后连接 c 必须不可再被使用。

type HostClient

  1. type HostClient struct {
  2. // 以逗号分隔的上游 HTTP 服务器 host 地址列表,通过轮询传递给 Dial//// 如果默认的 dialer 被使用,每一个地址都需要包含端口。// 例子://// - foobar.com:80// - foobar.com:443// - foobar.com:8080
  3. Addr string// 客户端名,用于 User-Agent 请求头。
  4. Name string// 建立到指定 host 的新连接后的回调函数。//// 如果未被设置,则会使用默认 Dial 函数。
  5. Dial DialFunc
  6. // 若被设为 true ,则会试图连接 ipv4 和 ipv6 的地址。//// 这个选项仅在使用默认 TCP dialer 时有效,// 例如:Dial 为空。//// 默认情况下客户端仅会连接 ipv4 地址,// 因为 ipv6 在世界上的大多数网络中都仍然不可用 :)
  7. DialDualStack bool// 是否使用 TLS 。
  8. IsTLS bool// 可选的 TLS 配置。
  9. TLSConfig *tls.Config
  10. // 每个 host 可以被建立的最大连接数。//// 如果未被设置,则使用默认的 DefaultMaxConnsPerHost 。
  11. MaxConns int// 在这个时间间隔后, keep-alive 连接会被关闭。// 默认值为无限制。
  12. MaxConnDuration time.Duration
  13. // 在这个时间间隔后,空闲的 keep-alive 连接会被关闭。// 默认值为 DefaultMaxIdleConnDuration 。
  14. MaxIdleConnDuration time.Duration
  15. // 每个连接响应读取时的缓冲大小。// 这个值也限制了最大头大小。//// 默认值为 0 。
  16. ReadBufferSize int// 每个连接请求写入时的缓冲大小。//// 默认值为 0 。
  17. WriteBufferSize int// 完整的响应读取(包含响应体)可用的最大时间。//// 默认为无限制。
  18. ReadTimeout time.Duration
  19. // 完整的请求写入(包含请求体)可用的最大时间。//// 默认为无限制。
  20. WriteTimeout time.Duration
  21. // 相应体的最大大小。//// 当该值大于 0 ,且相应体超过它时,客户端返回 ErrBodyTooLarge 。// 默认为无限制。
  22. MaxResponseBodySize int
  23. DisableHeaderNamesNormalizing bool// 包含被过滤或未导出的属性
  24. }

HostClient 均衡地向列于 Addr 中的 host 发起请求。

禁止拷贝 HostClient 实例。应使用创建新的实例。

在多个运行的 goroutine 间执行 HostClient 方法是安全的。

例子:

  1. package main
  2. import (
  3. "log""github.com/valyala/fasthttp"
  4. )
  5. func main() {
  6. // 准备一个客户端,用于通过监听于 localhost:8080 的 HTTP 代理获取网页
  7. c := &fasthttp.HostClient{
  8. Addr: "localhost:8080",
  9. }
  10. // 使用本地代理获取谷歌页面。
  11. statusCode, body, err := c.Get(nil, "http://google.com/foo/bar")
  12. if err != nil {
  13. log.Fatalf("Error when loading google page through local proxy: %s", err)
  14. }
  15. if statusCode != fasthttp.StatusOK {
  16. log.Fatalf("Unexpected status code: %d. Expecting %d", statusCode, fasthttp.StatusOK)
  17. }
  18. useResponseBody(body)
  19. // 通过本地代理获取 foobar 页面。重用 body 缓冲。
  20. statusCode, body, err = c.Get(body, "http://foobar.com/google/com")
  21. if err != nil {
  22. log.Fatalf("Error when loading foobar page through local proxy: %s", err)
  23. }
  24. if statusCode != fasthttp.StatusOK {
  25. log.Fatalf("Unexpected status code: %d. Expecting %d", statusCode, fasthttp.StatusOK)
  26. }
  27. useResponseBody(body)
  28. }
  29. func useResponseBody(body []byte) {
  30. // 处理 body
  31. }

func (*HostClient) Do

  1. 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

  1. 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

  1. 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

  1. 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

  1. 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

  1. 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

  1. func (c *HostClient) LastUseTime() time.Time

LastUseTime 返回客户端最后被使用的时间。

func (*HostClient) PendingRequests

  1. func (c *HostClient) PendingRequests() int

PendingRequests 返回正在执行的请求数。

func (*HostClient) Post

  1. 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

  1. type Logger interface {
  2. // Printf 必须与 log.Printf 有相同的语义。
  3. Printf(format string, args ...interface{})
  4. }

Logger 被用于记录格式化信息日志。

type PathRewriteFunc

  1. type PathRewriteFunc func(ctx *RequestCtx) []byte

PathRewriteFunc 必须返回基于 ctx.Path() 的新请求路径。

该函数用于在 FS 中转义当前请求路径至相对于 FS.Root 的相对路径。

处于安全原因,返回的路径中不允许包含 '/../' 子字符串。

func NewPathPrefixStripper

  1. 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

  1. 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

  1. type PipelineClient struct {
  2. // 连接的 host 的地址
  3. Addr string// 连接至 Addr 的最大并发数。//// 默认为单连接。
  4. MaxConns int// 单个连接至 Addr 的最大等待管道请求数量。//// 默认为 DefaultMaxPendingRequests 。
  5. MaxPendingRequests int// 在批量发送管道请求至服务器前的最大延时。//// 默认为无延时。
  6. MaxBatchDelay time.Duration
  7. /// 建立到指定 host 的新连接后的回调函数。//// 如果未被设置,则会使用默认 Dial 函数。
  8. Dial DialFunc
  9. // 若被设为 true ,则会试图连接 ipv4 和 ipv6 的地址。//// 这个选项仅在使用默认 TCP dialer 时有效,// 例如:Dial 为空。//// 默认情况下客户端仅会连接 ipv4 地址,// 因为 ipv6 在世界上的大多数网络中都仍然不可用 :)
  10. DialDualStack bool// 是否使用 TLS 。
  11. IsTLS bool// 可选的 TLS 配置。
  12. TLSConfig *tls.Config
  13. // 在这个时间间隔后,空闲的 keep-alive 连接会被关闭。// 默认值为 DefaultMaxIdleConnDuration 。
  14. MaxIdleConnDuration time.Duration
  15. // 每个连接响应读取时的缓冲大小。// 这个值也限制了最大头大小。//// 默认值为 0 。
  16. ReadBufferSize int// 每个连接请求写入时的缓冲大小。//// 默认值为 0 。
  17. WriteBufferSize int// 完整的响应读取(包含响应体)可用的最大时间。//// 默认为无限制。
  18. ReadTimeout time.Duration
  19. // 完整的请求写入(包含请求体)可用的最大时间。//// 默认为无限制。
  20. WriteTimeout time.Duration
  21. // 用于记录客户端错误的日志记录器。//// 默认为标准 log 库。
  22. Logger Logger
  23. // 包含被过滤或未导出的属性
  24. }

PipelineClient 通过一个指定的并发连接限制数,来发送请求。

这个客户端可能被用于高负载的 RPC 系统。更多详情参阅 https://en.wikipedia.org/wiki/HTTP_pipelining 。

禁止拷贝 PipelineClient 实例。应该创建新实例。

在运行的 goroutine 间调用 PipelineClient 方法是安全的。

func (*PipelineClient) Do

  1. 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

  1. 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

  1. 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

  1. func (c *PipelineClient) PendingRequests() int

PendingRequests 返回正在执行的请求数。

type Request

  1. type Request struct {
  2. // 请求头//// 按值拷贝 Header 是禁止的。应使用指针。
  3. Header RequestHeader
  4. // 包含被过滤或未导出的属性
  5. }

Request 代表一个 HTTP 请求。

禁止拷贝 Request 实例。应该创建新实例或使用 CopyTo 。

Request 实例必须不能再多个运行的 goroutine 间使用。

func AcquireRequest

  1. func AcquireRequest() *Request

AcquireRequest 从请求池中返回一个空的 Request 实例。

返回的 Request 实例在不再需要时可以通过 ReleaseRequest 释放回池。这可以降低垃圾回收负载。

func (*Request) AppendBody

  1. func (req *Request) AppendBody(p []byte)

AppendBody 追加 p 至请求体。

在函数返回后重用 p 是安全的。

func (*Request) AppendBodyString

fasthttp 文档手册的更多相关文章

  1. Vert.x Core 文档手册

    Vert.x Core 文档手册 中英对照表 Client:客户端 Server:服务器 Primitive:基本(描述类型) Writing:编写(有些地方译为开发) Fluent:流式的 Reac ...

  2. Vert.x Web 文档手册

    Vert.x Web 中英对照表 Container:容器 Micro-service:微服务 Bridge:桥接 Router:路由器 Route:路由 Sub-Route: 子路由 Handler ...

  3. Python相关在线文档手册地址

    Python相关: 五星推荐:http://python.usyiyi.cn/ Python 2.7官方中文文档:http://doc.iplaypy.com/python2/  英文:    htt ...

  4. MySQL Error Code文档手册---摘自MySQL官方网站

    This chapter lists the errors that may appear when you call MySQL from any host language. The first ...

  5. javacv教程文档手册开发指南汇总篇

    本章作为javacv技术栈系列文章汇总 前言 写了不少关于javacv的文章,不敢说精通 ,只能说对javacv很熟悉.虽然偶尔也提交pull request做做贡献,但是javacv包含的库实在太多 ...

  6. 接口文档管理工具rap

    git地址:  https://github.com/thx/RAP wiki : https://github.com/thx/RAP/wiki/home_cn 视频教程: http://thx.g ...

  7. NVelocity介绍,NVelocity中文手册文档及实例下载

    NVelocity是什么velocity英音:[vi'lɔsiti]美音:[və'lɑsətɪ]近在做一个项目,客户要求有网站模板功能,能够自主编辑网站的风格,因为这个系统是为政府部门做子站系统,举个 ...

  8. smarty3.0中文手册文档API及使用指南

    1.安装Smarty3.0一.什么是smarty?smarty是一个使用PHP写出来的模板PHP模板引擎,它提供了逻辑与外在内容的分离,简单的讲,目的就是要使用PHP程序员同美工分离,使用的程序员改变 ...

  9. 常用控件产品官方文档/手册/API列表 c#控件文档API列表 asp.net控件产品技术文档中文版

    .netCHARTING报表图表控件 文档帮助手册Ab3d.PowerToys 文档帮助手册Ab3d.Reader3ds 文档帮助手册ABViewer 文档帮助手册 (工程图纸文档管理系统)Activ ...

随机推荐

  1. asp.net core上使用redis探索(1)

    基于Ubuntu安装redis, 我找的一个很好的网站: https://www.digitalocean.com/community/tutorials/how-to-install-and-con ...

  2. javascript数组特性

    数组是一段线性分配的内存, 它通过整数计算偏移并访问其中的元素. 数组是一种性能出色的数据结构. 1.数组字面量 数组字面量提供了一种非常方便地创建新数组的表示法. 多个用逗号分隔的值的表达式. 数组 ...

  3. webservice入门简介

    为了梦想,努力奋斗! 追求卓越,成功就会在不经意间追上你 webservice入门简介 1.什么是webservice? webservice是一种跨编程语言和跨操作系统平台的远程调用技术. 所谓的远 ...

  4. Gson序列化问题导致的内存溢出,tip:Background sticky concurrent mark sweep GC freed

    问题原因,如果在json model里面放了非可序列化的对象就会导致这中问题,可序列化的就是那些基础数据类型和集合类型,如果在里面放个Android的Activity或者adapter这类类型字段,变 ...

  5. jquery文本框内容实时监控

    $("#A").bind("input propertychange", function () { $("#B").val($(this) ...

  6. Java面向对象进阶篇(包装类,不可变类)

    一. Java 8的包装类 Java中的8种基本数据类型不支持面向对象的变成机制,也不具备对象的特性:没有成员变量,方法可以调用.为此,Java为这8 种基本数据类型分别提供了对应的 包装类(Byte ...

  7. Webpack的配置与使用

    一.什么是Webpack?     WebPack可以看做是模块打包机.用于分析项目结构,找到JavaScript模块以及其它的一些浏览器不能直接运行的拓展语言(Scss,TypeScript等),将 ...

  8. 寻找DevExpress破解经历之旅

    众所周知DevExpress是收费的,但是破解版的也不少,近期公司需要做发票套打的功能让我找个打印工具,我寻思着DevExpress这个软件好像挺不错的,功能强大,看了下价格方面,好吧!2W多呢,市面 ...

  9. Dynamic 中修改实体中主字段的长度

    select EntityId,* from MetadataSchema.Entity where Name='dji_incidentaddress' SELECT TOP 100 [Attrib ...

  10. SpringMVC中的文件上传

    1. 配置图片服务器 一般图片会单独保存在图片服务器上, 本文为简化处理, 在Tomcat中配置一个路劲用于专门存放图片 在tomcat上配置图片虚拟目录,在tomcat下conf/server.xm ...