Start request
HTTP 메서드와 URL로 HTTP 요청을 시작합니다.
Copy // 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
메서드를 사용하여 프록시 시뮬레이션을 보여주는 간단한 예제를 소개합니다.
Copy // 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()) // 요청에서 받은 body 설정
statusCode, body, errs := agent.Bytes()
if len(errs) > 0 {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"errs": errs,
})
}
// 프록시에서 받은 상태 코드와 body 전달
return c.Status(statusCode).Send(body)
}
이 짧은 예제를 통해 *fiber.Client
사용이 매우 간단하고 직관적임을 알 수 있습니다.
✨ Agent
Agent
는 FastHTTP의 HostClient
를 기반으로 구축되었으며, 요청 메서드를 위한 전용 메서드와 같은 많은 편리한 헬퍼 메서드를 가지고 있습니다.
Parse
HostClient를 초기화합니다.
Copy 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
주어진 key: value
헤더를 설정합니다.
Copy 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
Copy agent.Set("k1", "v1").
SetBytesK([]byte("k1"), "v1").
SetBytesV("k1", []byte("v1")).
SetBytesKV([]byte("k2"), []byte("v2"))
// ...
Add
주어진 key: value
헤더를 추가합니다. 이 함수를 사용하면 같은 키를 가진 여러 헤더를 추가할 수 있습니다.
Copy 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
Copy 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
Connection: close
헤더를 추가합니다.
Copy func (a *Agent) ConnectionClose() *Agent
Copy agent.ConnectionClose()
// ...
UserAgent
User-Agent
헤더 값을 설정합니다.
Copy func (a *Agent) UserAgent(userAgent string) *Agent
func (a *Agent) UserAgentBytes(userAgent []byte) *Agent
Copy agent.UserAgent("fiber")
// ...
Cookie
key: value
형태로 쿠키를 설정합니다. Cookies
를 사용하여 여러 쿠키를 설정할 수 있습니다.
Copy 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
Copy agent.Cookie("k", "v")
agent.Cookies("k1", "v1", "k2", "v2")
// ...
Referer
Referer 헤더 값을 설정합니다.
Copy func (a *Agent) Referer(referer string) *Agent
func (a *Agent) RefererBytes(referer []byte) *Agent
Copy agent.Referer("https://docs.gofiber.io")
// ...
ContentType
Content-Type 헤더 값을 설정합니다.
Copy func (a *Agent) ContentType(contentType string) *Agent
func (a *Agent) ContentTypeBytes(contentType []byte) *Agent
Copy agent.ContentType("custom-type")
// ...
Host
Host 헤더를 설정합니다.
Copy func (a *Agent) Host(host string) *Agent
func (a *Agent) HostBytes(host []byte) *Agent
Copy agent.Host("example.com")
// ...
QueryString
URI 쿼리 스트링을 설정합니다.
Copy func (a *Agent) QueryString(queryString string) *Agent
func (a *Agent) QueryStringBytes(queryString []byte) *Agent
Copy agent.QueryString("foo=bar")
// ...
BasicAuth
HTTP Basic Auth를 사용하여 URI 사용자 이름과 암호를 설정합니다.
Copy func (a *Agent) BasicAuth(username, password string) *Agent
func (a *Agent) BasicAuthBytes(username, password []byte) *Agent
Copy agent.BasicAuth("foo", "bar")
// ...
Body
요청 본문을 설정하는 여러 가지 방법이 있습니다.
Copy func (a *Agent) BodyString(bodyString string) *Agent
func (a *Agent) Body(body []byte) *Agent
// BodyStream은 요청 본문 스트림과 선택적으로 본문 크기를 설정합니다.
//
// bodySize가 >= 0이면 bodyStream은 io.EOF를 반환하기 전에 정확히 bodySize 바이트를 제공해야 합니다.
//
// bodySize < 0이면 bodyStream은 io.EOF까지 읽습니다.
//
// bodyStream.Close()는 모든 본문 데이터를 읽은 후에 호출됩니다.
// io.Closer를 구현한 경우에만 해당됩니다.
//
// GET과 HEAD 요청은 본문을 가질 수 없습니다.
func (a *Agent) BodyStream(bodyStream io.Reader, bodySize int) *Agent
Copy agent.BodyString("foo=bar")
agent.Body([]byte("bar=baz"))
agent.BodyStream(strings.NewReader("body=stream"), -1)
// ...
JSON
ctype
매개변수로 Content-Type 헤더를 설정하여 JSON 요청을 보냅니다. ctype
이 전달되지 않으면 헤더가 application/json
으로 설정됩니다.
Copy func (a *Agent) JSON(v any, ctype ...string) *Agent
Copy agent.JSON(fiber.Map{"success": true})
// ...
XML
Content-Type 헤더를 application/xml
로 설정하여 XML 요청을 보냅니다.
Copy func (a *Agent) XML(v any) *Agent
Copy agent.XML(fiber.Map{"success": true})
// ...
Form
Content-Type 헤더를 application/x-www-form-urlencoded
로 설정하여 폼 요청을 보냅니다.
Copy // 인자가 nil이 아니면 본문과 함께 폼 요청을 보냅니다.
//
// 성능이 중요한 코드에서는 AcquireArgs를 통해 인자를 획득하고 수동으로 해제하는 것이 좋습니다.
func (a *Agent) Form(args *Args) *Agent
Copy args := AcquireArgs()
args.Set("foo", "bar")
agent.Form(args)
// ...
ReleaseArgs(args)
MultipartForm
Content-Type 헤더를 multipart/form-data
로 설정하여 멀티파트 폼 요청을 보냅니다. 이러한 요청은 키-값과 파일을 포함할 수 있습니다.
Copy // 키-값과 파일이 포함된 멀티파트 폼 요청을 보냅니다.
//
// 성능이 중요한 코드에서는 AcquireArgs를 통해 인자를 획득하고 수동으로 해제하는 것이 좋습니다.
func (a *Agent) MultipartForm(args *Args) *Agent
Copy args := AcquireArgs()
args.Set("foo", "bar")
agent.MultipartForm(args)
// ...
ReleaseArgs(args)
Fiber는 파일을 보내기 위한 몇 가지 메서드를 제공합니다. MultipartForm
전에 호출해야 합니다.
Boundary
멀티파트 폼 요청의 경계를 설정합니다.
Copy func (a *Agent) Boundary(boundary string) *Agent
Copy agent.Boundary("myBoundary")
.MultipartForm(nil)
// ...
SendFile(s)
파일을 읽고 멀티파트 폼 요청에 추가합니다. SendFiles를 사용하여 여러 파일을 추가할 수 있습니다.
Copy func (a *Agent) SendFile(filename string, fieldname ...string) *Agent
func (a *Agent) SendFiles(filenamesAndFieldnames ...string) *Agent
Copy agent.SendFile("f", "field name")
.SendFiles("f1", "field name1", "f2").
.MultipartForm(nil)
// ...
FileData
멀티파트 폼 요청에 파일 데이터를 추가합니다.
Copy // FormFile은 멀티파트 폼 파일을 나타냅니다.
type FormFile struct {
// Fieldname는 폼 파일의 필드 이름입니다.
Fieldname string
// Name은 폼 파일의 이름입니다.
Name string
// Content는 폼 파일의 내용입니다.
Content []byte
}
Copy // 멀티파트 폼 요청에 파일을 추가합니다.
//
// 성능이 중요한 코드에서는 AcquireFormFile을 통해 formFile을 획득하고 수동으로 해제하는 것이 좋습니다.
func (a *Agent) FileData(formFiles ...*FormFile) *Agent
Copy ff1 := &FormFile{"filename1", "field name1", []byte("content")}
ff2 := &FormFile{"filename2", "field name2", []byte("content")}
agent.FileData(ff1, ff2).
MultipartForm(nil)
// ...
Debug
Debug 모드는 io.writer
(기본값은 os.Stdout
)에 요청과 응답 세부 정보를 로깅합니다.
Copy func (a *Agent) Debug(w ...io.Writer) *Agent
Timeout
요청 제한 시간을 설정합니다.
Copy func (a *Agent) Timeout(timeout time.Duration) *Agent
Copy agent.Timeout(time.Second)
// ...
Reuse
Reuse는 한 번의 요청 후에 Agent 인스턴스를 다시 사용할 수 있게 해줍니다. 에이전트가 재사용 가능하면 더 이상 사용하지 않을 때 수동으로 해제해야 합니다.
Copy func (a *Agent) Reuse() *Agent
InsecureSkipVerify
InsecureSkipVerify는 Agent가 서버 인증서 체인과 호스트 이름을 확인할지 여부를 제어합니다.
Copy func (a *Agent) InsecureSkipVerify() *Agent
Copy agent.InsecureSkipVerify()
// ...
TLSConfig
TLS 구성을 설정합니다.
Copy func (a *Agent) TLSConfig(config *tls.Config) *Agent
Copy // TLS 인증서 생성
cer, _ := tls.LoadX509KeyPair("pem", "key")
config := &tls.Config{
Certificates: []tls.Certificate{cer},
}
agent.TLSConfig(config)
// ...
MaxRedirectsCount
GET과 HEAD에 대한 최대 리디렉션 수를 설정합니다.
Copy func (a *Agent) MaxRedirectsCount(count int) *Agent
Copy agent.MaxRedirectsCount(7)
// ...
JSONEncoder
사용자 정의 JSON 인코더를 설정합니다.
Copy func (a *Agent) JSONEncoder(jsonEncoder utils.JSONMarshal) *Agent
Copy agent.JSONEncoder(json.Marshal)
// ...
JSONDecoder
사용자 정의 JSON 디코더를 설정합니다.
Copy func (a *Agent) JSONDecoder(jsonDecoder utils.JSONUnmarshal) *Agent
Copy agent.JSONDecoder(json.Unmarshal)
// ...
Request
Agent 요청 인스턴스를 반환합니다.
Copy func (a *Agent) Request() *Request
Copy req := agent.Request()
// ...
SetResponse
Agent 인스턴스에 대한 사용자 정의 응답을 설정합니다. 성능이 중요한 코드에서는 AcquireResponse를 통해 사용자 정의 응답을 획득하고 수동으로 해제하는 것이 좋습니다.
Copy func (a *Agent) SetResponse(customResp *Response) *Agent
Copy resp := AcquireResponse()
agent.SetResponse(resp)
// ...
ReleaseResponse(resp)
응답 값 처리 예제
Copy // Fiber HTTP 클라이언트 에이전트 생성
agent := fiber.Get("https://httpbin.org/get")
// 결과를 저장할 응답 객체 획득
resp := fiber.AcquireResponse()
agent.SetResponse(resp)
// HTTP GET 요청 수행
code, body, errs := agent.String()
if errs != nil {
// 요청 중 발생하는 오류 처리
panic(errs)
}
// HTTP 응답 코드와 본문 출력
fmt.Println("Response Code:", code)
fmt.Println("Response Body:", body)
// 응답의 모든 헤더를 방문하고 출력
resp.Header.VisitAll(func(key, value []byte) {
fmt.Println("Header", string(key), "value", string(value))
})
// 리소스를 해제하기 위해 응답 해제
fiber.ReleaseResponse(resp)
Output:
Copy 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를 설정합니다. dest의 내용은 응답 본문으로 대체되며, dest가 너무 작으면 새 슬라이스가 할당됩니다.
Copy func (a *Agent) Dest(dest []byte) *Agent {
Copy agent.Dest(nil)
// ...
Bytes
URL의 상태 코드, 바이트 본문 및 오류를 반환합니다.
Copy func (a *Agent) Bytes() (code int, body []byte, errs []error)
Copy code, body, errs := agent.Bytes()
// ...
String
URL의 상태 코드, 문자열 본문 및 오류를 반환합니다.
Copy func (a *Agent) String() (int, string, []error)
Copy code, body, errs := agent.String()
// ...
Struct
URL의 상태 코드, 바이트 본문 및 오류를 반환합니다. 그리고 바이트 본문은 주어진 v로 역직렬화됩니다.
Copy func (a *Agent) Struct(v any) (code int, body []byte, errs []error)
Copy var d data
code, body, errs := agent.Struct(&d)
// ...
RetryIf
오류 후에 재시도를 시도해야 하는지 제어합니다. 기본적으로 fasthttp의 isIdempotent 함수를 사용합니다.
Copy func (a *Agent) RetryIf(retryIf RetryIfFunc) *Agent
Copy agent.Get("https://example.com").RetryIf(func (req *fiber.Request) bool {
return req.URI() == "https://example.com"
})
// ...