zoukankan      html  css  js  c++  java
  • fasthttp 文档手册

    fasthttp 文档手册

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

    常量

    const (
        CompressNoCompression      = flate.NoCompression
        CompressBestSpeed          = flate.BestSpeed
        CompressBestCompression    = flate.BestCompression
        CompressDefaultCompression = flate.DefaultCompression
    )

    所支持的压缩级别。

    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 状态吗。

    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 连接被关闭前默认的持续时间。

    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


  • 相关阅读:
    EF的四种开发模式
    EF4.0、4.3创建表达式树状动态查询总结
    使用vs2010复制粘贴代码时特别卡用一段时间就特别卡重启也没用
    vs2012运行项目提示无法连接 asp.net development server的解决方案
    泛组件技术
    intellij idea 编译 kafka 源码
    mycat 入门使用例子
    单机器搭建 zk 集群
    redis 版的 hello world
    zk observer 节点
  • 原文地址:https://www.cnblogs.com/zhangboyu/p/7452735.html
Copyright © 2011-2022 走看看