跳到主要内容
版本: v2.x

🌎 客户端

发起请求

使用 HTTP 方法和 URL 发起 HTTP 请求。

签名
// Client http methods
func (c *Client) Get(url string) *Agent
func (c *Client) Head(url string) *Agent
func (c *Client) Post(url string) *Agent
func (c *Client) Put(url string) *Agent
func (c *Client) Patch(url string) *Agent
func (c *Client) Delete(url string) *Agent

这里我们通过一个简短的示例,演示如何使用我们的 *fiber.Agent 方法来模拟代理。

// Get something
func getSomething(c *fiber.Ctx) (err error) {
agent := fiber.Get("<URL>")
statusCode, body, errs := agent.Bytes()
if len(errs) > 0 {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"errs": errs,
})
}

var something fiber.Map
err = json.Unmarshal(body, &something)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"err": err,
})
}

return c.Status(statusCode).JSON(something)
}

// Post something
func createSomething(c *fiber.Ctx) (err error) {
agent := fiber.Post("<URL>")
agent.Body(c.Body()) // set body received by request
statusCode, body, errs := agent.Bytes()
if len(errs) > 0 {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"errs": errs,
})
}

// pass status code and body received by the proxy
return c.Status(statusCode).Send(body)
}

基于这个简短的示例,我们可以看到使用 *fiber.Client 非常简单直观。

✨ Agent

Agent 构建于 FastHTTP 的 HostClient 之上,后者拥有许多方便的辅助方法,例如专门用于不同请求方法的方法。

Parse

Parse 初始化一个 HostClient。

Parse
a := AcquireAgent()
req := a.Request()
req.Header.SetMethod(MethodGet)
req.SetRequestURI("http://example.com")

if err := a.Parse(); err != nil {
panic(err)
}

code, body, errs := a.Bytes() // ...

Set

Set 设置给定的 key: value 请求头。

签名
func (a *Agent) Set(k, v string) *Agent
func (a *Agent) SetBytesK(k []byte, v string) *Agent
func (a *Agent) SetBytesV(k string, v []byte) *Agent
func (a *Agent) SetBytesKV(k []byte, v []byte) *Agent
示例
agent.Set("k1", "v1").
SetBytesK([]byte("k1"), "v1").
SetBytesV("k1", []byte("v1")).
SetBytesKV([]byte("k2"), []byte("v2"))
// ...

Add

Add 添加给定的 key: value 请求头。可以使用此函数添加具有相同键的多个请求头。

签名
func (a *Agent) Add(k, v string) *Agent
func (a *Agent) AddBytesK(k []byte, v string) *Agent
func (a *Agent) AddBytesV(k string, v []byte) *Agent
func (a *Agent) AddBytesKV(k []byte, v []byte) *Agent
示例
agent.Add("k1", "v1").
AddBytesK([]byte("k1"), "v1").
AddBytesV("k1", []byte("v1")).
AddBytesKV([]byte("k2"), []byte("v2"))
// Headers:
// K1: v1
// K1: v1
// K1: v1
// K2: v2

ConnectionClose

ConnectionClose 添加 Connection: close 请求头。

签名
func (a *Agent) ConnectionClose() *Agent
示例
agent.ConnectionClose()
// ...

UserAgent

UserAgent 设置 User-Agent 请求头的值。

签名
func (a *Agent) UserAgent(userAgent string) *Agent
func (a *Agent) UserAgentBytes(userAgent []byte) *Agent
示例
agent.UserAgent("fiber")
// ...

Cookie 以 key: value 的形式设置一个 cookie。Cookies 可用于设置多个 cookie。

签名
func (a *Agent) Cookie(key, value string) *Agent
func (a *Agent) CookieBytesK(key []byte, value string) *Agent
func (a *Agent) CookieBytesKV(key, value []byte) *Agent
func (a *Agent) Cookies(kv ...string) *Agent
func (a *Agent) CookiesBytesKV(kv ...[]byte) *Agent
示例
agent.Cookie("k", "v")
agent.Cookies("k1", "v1", "k2", "v2")
// ...

Referer

Referer 设置 Referer 请求头的值。

签名
func (a *Agent) Referer(referer string) *Agent
func (a *Agent) RefererBytes(referer []byte) *Agent
示例
agent.Referer("https://docs.fiber.org.cn")
// ...

ContentType

ContentType 设置 Content-Type 请求头的值。

签名
func (a *Agent) ContentType(contentType string) *Agent
func (a *Agent) ContentTypeBytes(contentType []byte) *Agent
示例
agent.ContentType("custom-type")
// ...

Host

Host 设置 Host 请求头。

签名
func (a *Agent) Host(host string) *Agent
func (a *Agent) HostBytes(host []byte) *Agent
示例
agent.Host("example.com")
// ...

QueryString

QueryString 设置 URI 查询字符串。

签名
func (a *Agent) QueryString(queryString string) *Agent
func (a *Agent) QueryStringBytes(queryString []byte) *Agent
示例
agent.QueryString("foo=bar")
// ...

BasicAuth

BasicAuth 使用 HTTP 基本认证设置 URI 用户名和密码。

签名
func (a *Agent) BasicAuth(username, password string) *Agent
func (a *Agent) BasicAuthBytes(username, password []byte) *Agent
示例
agent.BasicAuth("foo", "bar")
// ...

Body

有几种方法可以设置请求体。

签名
func (a *Agent) BodyString(bodyString string) *Agent
func (a *Agent) Body(body []byte) *Agent

// BodyStream sets request body stream and, optionally body size.
//
// If bodySize is >= 0, then the bodyStream must provide exactly bodySize bytes
// before returning io.EOF.
//
// If bodySize < 0, then bodyStream is read until io.EOF.
//
// bodyStream.Close() is called after finishing reading all body data
// if it implements io.Closer.
//
// Note that GET and HEAD requests cannot have body.
func (a *Agent) BodyStream(bodyStream io.Reader, bodySize int) *Agent
示例
agent.BodyString("foo=bar")
agent.Body([]byte("bar=baz"))
agent.BodyStream(strings.NewReader("body=stream"), -1)
// ...

JSON

JSON 发送 JSON 请求,方法是将 Content-Type 请求头设置为 ctype 参数。如果没有传入 ctype,则请求头设置为 application/json

签名
func (a *Agent) JSON(v interface{}, ctype ...string) *Agent
示例
agent.JSON(fiber.Map{"success": true})
// ...

XML

XML 发送 XML 请求,方法是将 Content-Type 请求头设置为 application/xml

签名
func (a *Agent) XML(v interface{}) *Agent
示例
agent.XML(fiber.Map{"success": true})
// ...

Form

Form 发送表单请求,方法是将 Content-Type 请求头设置为 application/x-www-form-urlencoded

签名
// Form sends form request with body if args is non-nil.
//
// It is recommended obtaining args via AcquireArgs and release it
// manually in performance-critical code.
func (a *Agent) Form(args *Args) *Agent
示例
args := AcquireArgs()
args.Set("foo", "bar")

agent.Form(args)
// ...
ReleaseArgs(args)

MultipartForm

MultipartForm 发送 multipart 表单请求,方法是将 Content-Type 请求头设置为 multipart/form-data。这些请求可以包含键值对和文件。

签名
// MultipartForm sends multipart form request with k-v and files.
//
// It is recommended to obtain args via AcquireArgs and release it
// manually in performance-critical code.
func (a *Agent) MultipartForm(args *Args) *Agent
示例
args := AcquireArgs()
args.Set("foo", "bar")

agent.MultipartForm(args)
// ...
ReleaseArgs(args)

Fiber 提供了几种发送文件的方法。请注意,它们必须在调用 MultipartForm 之前调用。

Boundary

Boundary 设置 multipart 表单请求的边界。

签名
func (a *Agent) Boundary(boundary string) *Agent
示例
agent.Boundary("myBoundary")
.MultipartForm(nil)
// ...

SendFile(s)

SendFile 读取文件并将其附加到 multipart 表单请求。Sendfiles 可用于附加多个文件。

签名
func (a *Agent) SendFile(filename string, fieldname ...string) *Agent
func (a *Agent) SendFiles(filenamesAndFieldnames ...string) *Agent
示例
agent.SendFile("f", "field name")
.SendFiles("f1", "field name1", "f2").
.MultipartForm(nil)
// ...

FileData

FileData 为 multipart 表单请求附加文件数据。

// FormFile represents multipart form file
type FormFile struct {
// Fieldname is form file's field name
Fieldname string
// Name is form file's name
Name string
// Content is form file's content
Content []byte
}
签名
// FileData appends files for multipart form request.
//
// It is recommended obtaining formFile via AcquireFormFile and release it
// manually in performance-critical code.
func (a *Agent) FileData(formFiles ...*FormFile) *Agent
示例
ff1 := &FormFile{"filename1", "field name1", []byte("content")}
ff2 := &FormFile{"filename2", "field name2", []byte("content")}
agent.FileData(ff1, ff2).
MultipartForm(nil)
// ...

Debug

调试模式启用将请求和响应详情记录到 io.writer(默认为 os.Stdout)。

签名
func (a *Agent) Debug(w ...io.Writer) *Agent
示例
agent.Debug()
// ...

Timeout

Timeout 设置请求超时时长。

签名
func (a *Agent) Timeout(timeout time.Duration) *Agent
示例
agent.Timeout(time.Second)
// ...

Reuse

Reuse 允许 Agent 实例在一个请求后再次使用。如果 agent 可重用,则在不再使用时应手动释放它。

签名
func (a *Agent) Reuse() *Agent
示例
agent.Reuse()
// ...

InsecureSkipVerify

InsecureSkipVerify 控制 Agent 是否验证服务器证书链和主机名。

签名
func (a *Agent) InsecureSkipVerify() *Agent
示例
agent.InsecureSkipVerify()
// ...

TLSConfig

TLSConfig 设置 TLS 配置。

签名
func (a *Agent) TLSConfig(config *tls.Config) *Agent
示例
// Create tls certificate
cer, _ := tls.LoadX509KeyPair("pem", "key")

config := &tls.Config{
Certificates: []tls.Certificate{cer},
}

agent.TLSConfig(config)
// ...

MaxRedirectsCount

MaxRedirectsCount 设置 GET 和 HEAD 请求的最大重定向次数。

签名
func (a *Agent) MaxRedirectsCount(count int) *Agent
示例
agent.MaxRedirectsCount(7)
// ...

JSONEncoder

JSONEncoder 设置自定义 JSON 编码器。

签名
func (a *Agent) JSONEncoder(jsonEncoder utils.JSONMarshal) *Agent
示例
agent.JSONEncoder(json.Marshal)
// ...

JSONDecoder

JSONDecoder 设置自定义 JSON 解码器。

签名
func (a *Agent) JSONDecoder(jsonDecoder utils.JSONUnmarshal) *Agent
示例
agent.JSONDecoder(json.Unmarshal)
// ...

Request

Request 返回 Agent 请求实例。

签名
func (a *Agent) Request() *Request
示例
req := agent.Request()
// ...

SetResponse

SetResponse 为 Agent 实例设置自定义响应。在性能关键的代码中,建议通过 AcquireResponse 获取自定义响应并手动释放它。

签名
func (a *Agent) SetResponse(customResp *Response) *Agent
示例
resp := AcquireResponse()
agent.SetResponse(resp)
// ...
ReleaseResponse(resp)
处理响应值的示例
处理响应示例
// Create a Fiber HTTP client agent
agent := fiber.Get("https://httpbin.org/get")

// Acquire a response object to store the result
resp := fiber.AcquireResponse()
agent.SetResponse(resp)

// Perform the HTTP GET request
code, body, errs := agent.String()
if errs != nil {
// Handle any errors that occur during the request
panic(errs)
}

// Print the HTTP response code and body
fmt.Println("Response Code:", code)
fmt.Println("Response Body:", body)

// Visit and print all the headers in the response
resp.Header.VisitAll(func(key, value []byte) {
fmt.Println("Header", string(key), "value", string(value))
})

// Release the response to free up resources
fiber.ReleaseResponse(resp)

输出

输出
Response Code: 200
Response Body: {
"args": {},
"headers": {
"Host": "httpbin.org",
"User-Agent": "fiber",
"X-Amzn-Trace-Id": "Root=1-653763d0-2555d5ba3838f1e9092f9f72"
},
"origin": "83.137.191.1",
"url": "https://httpbin.org/get"
}

Header Content-Length value 226
Header Content-Type value application/json
Header Server value gunicorn/19.9.0
Header Date value Tue, 24 Oct 2023 06:27:28 GMT
Header Connection value keep-alive
Header Access-Control-Allow-Origin value *
Header Access-Control-Allow-Credentials value true

Dest

Dest 设置自定义目标。目标的内容将被响应体替换,如果目标太小,将分配新的切片。

签名
func (a *Agent) Dest(dest []byte) *Agent {
示例
agent.Dest(nil)
// ...

Bytes

Bytes 返回 URL 的状态码、字节体和错误。

签名
func (a *Agent) Bytes() (code int, body []byte, errs []error)
示例
code, body, errs := agent.Bytes()
// ...

String

String 返回 URL 的状态码、字符串体和错误。

签名
func (a *Agent) String() (int, string, []error)
示例
code, body, errs := agent.String()
// ...

Struct

Struct 返回 URL 的状态码、字节体和错误。并且字节体将被解组到给定的 v 中。

签名
func (a *Agent) Struct(v interface{}) (code int, body []byte, errs []error)
示例
var d data
code, body, errs := agent.Struct(&d)
// ...

RetryIf

RetryIf 控制在发生错误后是否应尝试重试。默认情况下,将使用 fasthttp 中的 isIdempotent 函数。

签名
func (a *Agent) RetryIf(retryIf RetryIfFunc) *Agent
示例
agent.Get("https://example.com").RetryIf(func (req *fiber.Request) bool {
return req.URI() == "https://example.com"
})
// ...