Accepts
클라이언트가 지정된 extensions 또는 content types 이 허용되는지 확인합니다.
Copy func (c *Ctx) Accepts(offers ...string) string
func (c *Ctx) AcceptsCharsets(offers ...string) string
func (c *Ctx) AcceptsEncodings(offers ...string) string
func (c *Ctx) AcceptsLanguages(offers ...string) string
Copy // Accept: text/html, application/json; q=0.8, text/plain; q=0.5; charset="utf-8"
app.Get("/", func(c \*fiber.Ctx) error {
c.Accepts("html") // "html"
c.Accepts("text/html") // "text/html"
c.Accepts("json", "text") // "json"
c.Accepts("application/json") // "application/json"
c.Accepts("text/plain", "application/json") // "application/json", due to quality
c.Accepts("image/png") // ""
c.Accepts("png") // ""
// ...
})
Copy // Accept: text/html, text/*, application/json, */*; q=0
app.Get("/", func(c \*fiber.Ctx) error {
c.Accepts("text/plain", "application/json") // "application/json", due to specificity
c.Accepts("application/json", "text/html") // "text/html", due to first match
c.Accepts("image/png") // "", due to \*/\* without q factor 0 is Not Acceptable
// ...
})
미디어 타입 매개변수가 지원됩니다.
Copy // Accept: text/plain, application/json; version=1; foo=bar
app.Get("/", func(c \*fiber.Ctx) error {
// Accept 의 추가 매개변수는 무시됩니다
c.Accepts("text/plain;format=flowed") // "text/plain;format=flowed"
// 지정된 offer는 Accept 타입에 존재하는 모든 매개변수를 포함해야 합니다
c.Accepts("application/json") // ""
// 매개변수 순서와 대소문자는 중요하지 않습니다. 값의 따옴표는 제거됩니다.
c.Accepts(\`application/json;foo="bar";VERSION=1\`) // "application/json;foo="bar";VERSION=1"
})
Copy // Accept: text/plain;format=flowed;q=0.9, text/plain
// "text/plain;format=flowed" 를 다른 text/plain 보다 덜 선호함을 의미
app.Get("/", func(c \*fiber.Ctx) error {
// 주의: offers 가 나열되는 순서가 중요합니다.
// 클라이언트는 format=flowed를 덜 원한다고 지정했지만,
// text/plain Accept는 "text/plain;format=flowed" 와 먼저 매칭되므로 그것이 리턴됩니다.
c.Accepts("text/plain;format=flowed", "text/plain") // "text/plain;format=flowed"
// 여기선 예상대로 동작합니다:
c.Accepts("text/plain", "text/plain;format=flowed") // "text/plain"
})
Fiber는 다른 accept 헤더에 대해 유사한 함수들을 제공합니다.
Copy // Accept-Charset: utf-8, iso-8859-1;q=0.2
// Accept-Encoding: gzip, compress;q=0.2
// Accept-Language: en;q=0.8, nl, ru
app.Get("/", func(c \*fiber.Ctx) error {
c.AcceptsCharsets("utf-16", "iso-8859-1")
// "iso-8859-1"
c.AcceptsEncodings("compress", "br")
// "compress"
c.AcceptsLanguages("pt", "nl", "ru")
// "nl"
// ...
})
App
*App 참조를 반환하여 모든 애플리케이션 설정에 쉽게 접근할 수 있도록 합니다.
Copy func (c \*Ctx) App() \*App
Copy app.Get("/stack", func(c \*fiber.Ctx) error {
return c.JSON(c.App().Stack())
})
Append
응답의 HTTP 헤더 필드에 지정된 value 를 추가합니다.
만약 헤더가 설정되지 않았다면 , 지정된 값으로 헤더를 생성합니다.
Copy func (c \*Ctx) Append(field string, values ...string)
Copy app.Get("/", func(c \*fiber.Ctx) error {
c.Append("Link", "http://google.com", "http://localhost")
// => Link: http://localhost, http://google.com
c.Append("Link", "Test")
// => Link: http://localhost, http://google.com, Test
// ...
})
Attachment
Content-Disposition 응답 헤더 필드를 attachment
로 설정합니다.
Copy func (c \*Ctx) Attachment(filename ...string)
Copy app.Get("/", func(c \*fiber.Ctx) error {
c.Attachment()
// => Content-Disposition: attachment
c.Attachment("./upload/images/logo.png")
// => Content-Disposition: attachment; filename="logo.png"
// => Content-Type: image/png
// ...
})
AutoFormat
Accept HTTP 헤더를 기준으로 내용 협상(content-negotiation)을 수행합니다. 적절한 형식을 선택하기 위해 Accepts 를 사용합니다. 지원되는 내용 타입은 text/html
, text/plain
, application/json
, application/xml
입니다. 더 유연한 내용 협상을 위해서는 Format 을 사용하세요.
헤더가 지정되지 않았거나 , 적절한 형식이 없는 경우 text/plain 이 사용됩니다.
Copy func (c \*Ctx) AutoFormat(body interface{}) error
Copy app.Get("/", func(c \*fiber.Ctx) error {
// Accept: text/plain
c.AutoFormat("Hello, World!")
// => Hello, World!
// Accept: text/html
c.AutoFormat("Hello, World!")
// => <p>Hello, World!</p>
type User struct {
Name string
}
user := User{"John Doe"}
// Accept: application/json
c.AutoFormat(user)
// => {"Name":"John Doe"}
// Accept: application/xml
c.AutoFormat(user)
// => <User><Name>John Doe</Name></User>
// ..
})
BaseURL
string
으로 기본 URL(protocol + host ) 을 반환합니다.
Copy func (c \*Ctx) BaseURL() string
Copy // GET https://example.com/page#chapter-1
app.Get("/", func(c \*fiber.Ctx) error {
c.BaseURL() // https://example.com
// ...
})
Bind
Bind은 request/response body, query parameters, URL parameters, cookies 등 여러 것들을 지원하는 메서드입니다. Bind 구조체의 포인터를 반환하며, request/response 데이터를 바인딩하기 위한 모든 메서드를 포함하고 있습니다.
자세한 정보는 Bind 문서를 참조하세요.
Copy func (c \*Ctx) Bind() \*Bind
Copy app.Post("/", func(c \*fiber.Ctx) error {
user := new(User)
// 요청 body를 구조체에 바인딩:
return c.Bind().Body(user)
})
Body
요청 헤더에 따라 body 바이트를 파일 압축 해제하려고 시도합니다.
Content-Encoding
헤더가 전송되지 않으면 BodyRaw 처럼 동작합니다.
Copy func (c \*Ctx) Body() []byte
Copy // echo 'user=john' | gzip | curl -v -i --data-binary @- -H "Content-Encoding: gzip" http://localhost:8080
app.Post("/", func(c \*fiber.Ctx) error {
// Content-Encoding에 따라 POST 요청에서 body를 압축 해제하고 원시 콘텐츠를 반환:
return c.Send(c.Body()) // []byte("user=john")
})
반환된 값은 핸들러 내에서만 유효합니다. 참조를 저장하지 마세요. 복사본을 만들거나 대신 Immutable
설정을 사용하세요. 더 읽기...
BodyRaw
원시 요청 body 를 반환합니다.
Copy func (c \*Ctx) BodyRaw() []byte
Copy // curl -X POST http://localhost:8080 -d user=john
app.Post("/", func(c \*fiber.Ctx) error {
// POST 요청에서 원시 body 가져오기:
return c.Send(c.BodyRaw()) // []byte("user=john")
})
반환된 값은 핸들러 내에서만 유효합니다. 참조를 저장하지 마세요. 복사본을 만들거나 대신 Immutable
설정을 사용하세요. 더 읽기...
ClearCookie
클라이언트 쿠키를 만료시킵니다(빈 문자열이면 모든 쿠키 )
Copy func (c \*Ctx) ClearCookie(key ...string)
Copy app.Get("/", func(c \*fiber.Ctx) error {
// 모든 쿠키 삭제:
c.ClearCookie()
// 이름으로 특정 쿠키 만료:
c.ClearCookie("user")
// 이름으로 여러 쿠키 만료:
c.ClearCookie("token", "session", "track_id", "version")
// ...
})
웹 브라우저 및 기타 호환 클라이언트는 쿠키를 생성할 때 expires 및 maxAge를 제외하고 지정된 옵션이 동일한 경우에만 쿠키를 삭제합니다. ClearCookie는 이러한 값을 자동으로 설정하지 않습니다 - 아래와 같은 기술을 사용하여 쿠키가 삭제되도록 해야 합니다.
Copy app.Get("/set", func(c \*fiber.Ctx) error {
c.Cookie(&fiber.Cookie{
Name: "token",
Value: "randomvalue",
Expires: time.Now().Add(24 \* time.Hour),
HTTPOnly: true,
SameSite: "lax",
})
// ...
})
app.Get("/delete", func(c \*fiber.Ctx) error {
c.Cookie(&fiber.Cookie{
Name: "token",
// 만료일을 과거로 설정
Expires: time.Now().Add(-(time.Hour \* 2)),
HTTPOnly: true,
SameSite: "lax",
})
// ...
})
ClientHelloInfo
ClientHelloInfo는 GetCertificate 및 GetConfigForClient 콜백에서 애플리케이션 로직을 안내하기 위해 ClientHello 메시지의 정보를 포함합니다. 반반환된 구조체에 대한 자세한 정보는 ClientHelloInfo 구조체 문서를 참조할 수 있습니다.
Copy func (c *Ctx) ClientHelloInfo() *tls.ClientHelloInfo
Copy // GET http://example.com/hello
app.Get("/hello", func(c *fiber.Ctx) error {
chi := c.ClientHelloInfo()
// ...
})
Context
context.Context
인터페이스와 호환되는 *fasthttp.RequestCtx 를 반환하며, 이는 마감일, 취소 신호 및 기타 값들을 API 경계를 넘어 전달합니다.
Copy func (c *Ctx) Context() *fasthttp.RequestCtx
Cookie
쿠키 설정
Copy func (c *Ctx) Cookie(cookie *Cookie)
Copy type Cookie struct {
Name string `json:"name"`
Value string `json:"value"`
Path string `json:"path"`
Domain string `json:"domain"`
MaxAge int `json:"max_age"`
Expires time.Time `json:"expires"`
Secure bool `json:"secure"`
HTTPOnly bool `json:"http_only"`
SameSite string `json:"same_site"`
SessionOnly bool `json:"session_only"`
}
Copy app.Get("/", func(c *fiber.Ctx) error {
// 쿠키 생성
cookie := new(fiber.Cookie)
cookie.Name = "john"
cookie.Value = "doe"
cookie.Expires = time.Now().Add(24 * time.Hour)
// 쿠키 설정
c.Cookie(cookie)
// ...
})
Cookies
key로 쿠키 값을 가져옵니다. 쿠키 key가 존재하지 않으면 반환될 기본값을 전달할 수 있습니다.
Copy func (c *Ctx) Cookies(key string, defaultValue ...string) string
Copy app.Get("/", func(c *fiber.Ctx) error {
// key로 쿠키 가져오기:
c.Cookies("name") // "john"
c.Cookies("empty", "doe") // "doe"
// ...
})
반환된 값은 핸들러 내에서만 유효합니다. 참조를 저장하지 마세요. 복사본을 만들거나 대신 Immutable
설정을 사용하세요. 더 읽기...
Download
path에서 attachment
로 파일을 전송합니다.
일반적으로 브라우저는 사용자에게 다운로드하라는 메시지를 표시합니다. 기본적으로 Content-Disposition 헤더 filename=
매개변수는 파일 경로입니다(이는 일반적으로 브라우저 대화 상자에 표시됨 ).
filename 매개변수로 이 기본값을 재정의하세요.
Copy func (c *Ctx) Download(file string, filename ...string) error
Copy app.Get("/", func(c *fiber.Ctx) error {
return c.Download("./files/report-12345.pdf");
// => Download report-12345.pdf
return c.Download("./files/report-12345.pdf", "report.pdf");
// => Download report.pdf
})
Format
Accept HTTP 헤더를 기준으로 내용 협상(content-negotiation)을 수행합니다. MediaType
을 "default"
로 설정하여 기본 핸들러를 제공할 수 있습니다. 일치하는 offer가 없고 기본값이 제공되지 않으면 406(허용되지 않음) 응답이 전송됩니다. 핸들러가 선택되면 Content-Type이 자동으로 설정됩니다.
Accept 헤더가 지정되지 않으면 첫 번째 핸들러가 사용됩니다.
Copy func (c *Ctx) Format(handlers ...ResFmt) error
Copy // Accept: application/json => {"command":"eat","subject":"fruit"}
// Accept: text/plain => Eat Fruit!
// Accept: application/xml => Not Acceptable
app.Get("/no-default", func(c *fiber.Ctx) error {
return c.Format(
fiber.ResFmt{"application/json", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{
"command": "eat",
"subject": "fruit",
})
}},
fiber.ResFmt{"text/plain", func(c *fiber.Ctx) error {
return c.SendString("Eat Fruit!")
}},
)
})
// Accept: application/json => {"command":"eat","subject":"fruit"}
// Accept: text/plain => Eat Fruit!
// Accept: application/xml => Eat Fruit!
app.Get("/default", func(c *fiber.Ctx) error {
textHandler := func(c *fiber.Ctx) error {
return c.SendString("Eat Fruit!")
}
handlers := []fiber.ResFmt{
{"application/json", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{
"command": "eat",
"subject": "fruit",
})
}},
{"text/plain", textHandler},
{"default", textHandler},
}
return c.Format(handlers...)
})
FormFile
key로 지정된 첫 번째 파일이 반환됩니다.
Copy func (c *Ctx) FormFile(key string) (\*multipart.FileHeader, error)
Copy app.Post("/", func(c *fiber.Ctx) error {
// 폼 필드 "document"에서 첫 번째 파일 가져오기:
file, err := c.FormFile("document")
// 파일을 루트 디렉토리에 저장:
return c.SaveFile(file, fmt.Sprintf("./%s", file.Filename))
})
FormValue
key로 지정된 첫 번째 값이 반환됩니다.
Copy func (c *Ctx) FormValue(key string, defaultValue ...string) string
Copy app.Post("/", func(c *fiber.Ctx) error {
// 폼 필드 "name"에서 첫 번째 값 가져오기:
c.FormValue("name")
// => "john" 또는 존재하지 않으면 ""
// ..
})
반환된 값은 핸들러 내에서만 유효합니다. 참조를 저장하지 마세요. 복사본을 만들거나 대신 Immutable
설정을 사용하세요. 더 읽기...
Fresh
클라이언트의 캐시에 응답이 아직 새로운 경우 true 를 반환하고, 그렇지 않으면 클라이언트 캐시가 이제 오래되었고 전체 응답을 보내야 함을 나타내기 위해 false 를 반환합니다.
클라이언트가 end-to-end 새로고침 요청을 나타내기 위해 Cache-Control: no-cache 요청 헤더를 보내면 Fresh
는 이러한 요청을 투명하게 처리하기 위해 false를 반환합니다.
자세한 내용은 https://expressjs.com/en/4x/api.html#req.fresh 를 참조하세요.
Copy func (c *Ctx) Fresh() bool
Get
지정된 필드로 HTTP 요청 헤더를 반환합니다.
Copy func (c *Ctx) Get(key string, defaultValue ...string) string
Copy app.Get("/", func(c *fiber.Ctx) error {
c.Get("Content-Type") // "text/plain"
c.Get("CoNtEnT-TypE") // "text/plain"
c.Get("something", "john") // "john"
// ..
})
반환된 값은 핸들러 내에서만 유효합니다. 참조를 저장하지 마세요. 복사본을 만들거나 대신 Immutable
설정을 사용하세요. 더 읽기...
HTTP 요청 헤더를 맵으로 반환합니다. 헤더는 단일 요청에서 여러 번 설정될 수 있으므로, 맵의 값은 헤더의 다른 값을 모두 포함하는 문자열 슬라이스입니다.
Copy func (c *Ctx) GetReqHeaders() map[string][]string
반환된 값은 핸들러 내에서만 유효합니다. 참조를 저장하지 마세요. 복사본을 만들거나 대신 Immutable
설정을 사용하세요. 더 읽기...
지정된 필드로 HTTP 응답 헤더를 반환합니다.
Copy func (c *Ctx) GetRespHeader(key string, defaultValue ...string) string
Copy app.Get("/", func(c *fiber.Ctx) error {
c.GetRespHeader("X-Request-Id") // "8d7ad5e3-aaf3-450b-a241-2beb887efd54"
c.GetRespHeader("Content-Type") // "text/plain"
c.GetRespHeader("something", "john") // "john"
// ..
})
반환된 값은 핸들러 내에서만 유효합니다. 참조를 저장하지 마세요. 복사본을 만들거나 대신 Immutable
설정을 사용하세요. 더 읽기...
HTTP 응답 헤더를 맵으로 반환합니다. 헤더는 단일 요청에서 여러 번 설정될 수 있으므로, 맵의 값은 헤더의 다른 값을 모두 포함하는 문자열 슬라이스입니다.
Copy func (c *Ctx) GetRespHeaders() map[string][]string
반환된 값은 핸들러 내에서만 유효합니다. 참조를 저장하지 마세요. 복사본을 만들거나 대신 Immutable
설정을 사용하세요. 더 읽기...
GetRouteURL
매개변수와 함께 명명된 경로에 대한 URL을 생성합니다. URL은 "/user/1831"과 같이 상대적입니다.
Copy func (c *Ctx) GetRouteURL(routeName string, params fiber.Map) (string, error)
Copy app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Home page")
}).Name("home")
app.Get("/user/:id", func(c *fiber.Ctx) error {
return c.SendString(c.Params("id"))
}).Name("user.show")
app.Get("/test", func(c *fiber.Ctx) error {
location, _ := c.GetRouteURL("user.show", fiber.Map{"id": 1})
return c.SendString(location)
})
// /test 는 "/user/1" 를 반환
Host
Host HTTP 헤더에서 파생된 호스트를 반환합니다.
네트워크 컨텍스트에서 Host
는 연결에 사용되는 호스트 이름과 잠재적으로 포트 번호의 조합을 의미하는 반면, Hostname
는 포트 정보를 제외하고 네트워크에서 장치에 할당된 이름만을 의미합니다.
Copy func (c *Ctx) Host() string
Copy // GET http://google.com:8080/search
app.Get("/", func(c *fiber.Ctx) error {
c.Host() // "google.com:8080"
c.Hostname() // "google.com"
// ...
})
반환된 값은 핸들러 내에서만 유효합니다. 참조를 저장하지 마세요.
복사본을 만들거나 대신 Immutable
설정을 사용하세요. 더 읽기...
Hostname
Host HTTP 헤더에서 파생된 호스트 이름을 반환합니다.
Copy func (c *Ctx) Hostname() string
Copy // GET http://google.com/search
app.Get("/", func(c *fiber.Ctx) error {
c.Hostname() // "google.com"
// ...
})
반환된 값은 핸들러 내에서만 유효합니다. 참조를 저장하지 마세요.
복사본을 만들거나 대신 Immutable
설정을 사용하세요. 더 읽기...
IP
요청의 원격 IP 주소를 반환합니다.
Copy func (c *Ctx) IP() string
Copy app.Get("/", func(c *fiber.Ctx) error {
c.IP() // "127.0.0.1"
// ...
})
Fiber 앱에 프록시 요청 헤더를 등록하면 헤더의 IP 주소가 반환됩니다. (Fiber 구성)
Copy app := fiber.New(fiber.Config{
ProxyHeader: fiber.HeaderXForwardedFor,
})
IPs
X-Forwarded-For 요청 헤더에 지정된 IP 주소 배열을 반환합니다.
Copy func (c *Ctx) IPs() []string
Copy // X-Forwarded-For: proxy1, 127.0.0.1, proxy3
app.Get("/", func(c *fiber.Ctx) error {
c.IPs() // ["proxy1", "127.0.0.1", "proxy3"]
// ...
})
X-Forwarded-For 헤더를 부적절하게 사용하면 보안 위험이 될 수 있습니다. 자세한 내용은 보안 및 개인 정보 보호 문제 섹션을 참조하세요.
Is
들어오는 요청의 Content-Type HTTP 헤더 필드가 type 매개 변수로 지정된 MIME 유형 과 일치하면 일치하는 콘텐츠 유형 을 반환합니다.
요청에 본문(body) 이 없으면 false 를 반환합니다.
Copy func (c *Ctx) Is(extension string) bool
Copy // Content-Type: text/html; charset=utf-8
app.Get("/", func(c *fiber.Ctx) error {
c.Is("html") // true
c.Is(".html") // true
c.Is("json") // false
// ...
})
IsFromLocal
요청이 로컬 호스트에서 왔는지 여부를 반환합니다.
Copy func (c *Ctx) IsFromLocal() bool {
Copy
app.Get("/", func(c *fiber.Ctx) error {
// 요청이 localhost에서 온 경우 true를 반환하고 그렇지 않으면 false를 반환합니다
c.IsFromLocal()
// ...
})
IsProxyTrusted
원격 IP의 신뢰성을 확인합니다. EnableTrustedProxyCheck
가 false이면 true를 반환합니다. IsProxyTrusted는 프록시 범위와 IP 맵으로 원격 IP를 확인할 수 있습니다.
Copy func (c *Ctx) IsProxyTrusted() bool
Copy
app := fiber.New(fiber.Config{
// EnableTrustedProxyCheck는 신뢰할 수 있는 프록시 확인을 활성화합니다
EnableTrustedProxyCheck: true,
// TrustedProxies는 신뢰할 수 있는 프록시 IP 주소 목록입니다
TrustedProxies: []string{"0.8.0.0", "0.8.0.1"},
})
app.Get("/", func(c *fiber.Ctx) error {
// 요청이 신뢰할 수 있는 프록시에서 온 경우 true를 반환하고 그렇지 않으면 false를 반환합니다
c.IsProxyTrusted()
// ...
})
JSON
encoding/json 패키지를 사용하여 모든 interface 또는 string 을 JSON으로 변환합니다.
JSON은 컨텐츠 헤더를 ctype
매개변수로 설정합니다. ctype
이 전달되지 않으면 헤더가 application/json
으로 설정됩니다.
Copy func (c *Ctx) JSON(data interface{}, ctype ...string) error
Copy type SomeStruct struct {
Name string
Age uint8
}
app.Get("/json", func(c *fiber.Ctx) error {
// 데이터 구조체 생성:
data := SomeStruct{
Name: "Grame",
Age: 20,
}
return c.JSON(data)
// => Content-Type: application/json
// => "{"Name": "Grame", "Age": 20}"
return c.JSON(fiber.Map{
"name": "Grame",
"age": 20,
})
// => Content-Type: application/json
// => "{"name": "Grame", "age": 20}"
return c.JSON(fiber.Map{
"type": "https://example.com/probs/out-of-credit",
"title": "You do not have enough credit.",
"status": 403,
"detail": "Your current balance is 30, but that costs 50.",
"instance": "/account/12345/msgs/abc",
}, "application/problem+json")
// => Content-Type: application/problem+json
// => "{
// => "type": "https://example.com/probs/out-of-credit",
// => "title": "You do not have enough credit.",
// => "status": 403,
// => "detail": "Your current balance is 30, but that costs 50.",
// => "instance": "/account/12345/msgs/abc",
// => }"
})
JSONP
JSONP 지원이 포함된 JSON 응답을 보냅니다. 이 메서드는 JSONP 콜백 지원을 옵트인한다는 점을 제외하면 JSON과 동일합니다. 기본적으로 콜백 이름은 단순히 callback입니다.
메서드에 named string 을 전달하여 이를 재정의하세요.
Copy func (c *Ctx) JSONP(data interface{}, callback ...string) error
Copy type SomeStruct struct {
name string
age uint8
}
app.Get("/", func(c *fiber.Ctx) error {
// 데이터 구조체 생성:
data := SomeStruct{
name: "Grame",
age: 20,
}
return c.JSONP(data)
// => callback({"name": "Grame", "age": 20})
return c.JSONP(data, "customFunc")
// => customFunc({"name": "Grame", "age": 20})
})
Links
지정된 링크를 속성에 따라 연결하여 응답의 Link HTTP 헤더 필드를 채웁니다.
Copy func (c *Ctx) Links(link ...string)
Copy app.Get("/", func(c *fiber.Ctx) error {
c.Links(
"http://api.example.com/users?page=2", "next",
"http://api.example.com/users?page=5", "last",
)
// Link: <http://api.example.com/users?page=2>; rel="next",
// <http://api.example.com/users?page=5>; rel="last"
// ...
})
Locals
요청에 대해 범위가 지정되어 요청과 일치하는 경로에서만 사용할 수 있는 변수를 저장하는 메서드입니다.
특정 데이터를 다음 미들웨어로 전달하려는 경우에 유용합니다.
Copy func (c *Ctx) Locals(key interface{}, value ...interface{}) interface{}
Copy
// key는 이 패키지에 정의된 키에 대해 내보내지 않는 유형입니다.
// 이는 다른 패키지에 정의된 키와 충돌을 방지합니다.
type key int
// userKey는 Contexts에서 user.User 값에 대한 키입니다.
// 내보내지 않습니다. 클라이언트는 이 키를 직접 사용하는 대신
// user.NewContext 및 user.FromContext를 사용합니다.
var userKey key
app.Use(func(c *fiber.Ctx) error {
c.Locals(userKey, "admin")
return c.Next()
})
app.Get("/admin", func(c *fiber.Ctx) error {
if c.Locals(userKey) == "admin" {
return c.Status(fiber.StatusOK).SendString("Welcome, admin!")
}
return c.SendStatus(fiber.StatusForbidden)
})
Go의 제네릭 기능을 활용하는 Locals 메서드의 대체 버전도 사용할 수 있습니다. 이 버전은 요청의 컨텍스트 내에서 로컬 값을 더 구체적인 데이터 유형으로 조작하고 검색할 수 있습니다.
Copy func Locals[V any](c *Ctx, key interface{}, value ...V) V
Copy app.Use(func(c *Ctx) error {
fiber.Locals[string](c, "john", "doe")
fiber.Locals[int](c, "age", 18)
fiber.Locals[bool](c, "isHuman", true)
return c.Next()
})
app.Get("/test", func(c *Ctx) error {
fiber.Locals[string](c, "john") // "doe"
fiber.Locals[int](c, "age") // 18
fiber.Locals[bool](c, "isHuman") // true
return nil
})
애플리케이션 내에서 경로별 데이터를 더 잘 제어하기 위해 표준 형식과 제네릭 형식 모두에서 Locals 메서드를 이해하고 올바르게 구현해야 합니다.
Location
지정된 path 매개변수로 응답 Location HTTP 헤더를 설정합니다.
Copy func (c *Ctx) Location(path string)
Copy app.Post("/", func(c *fiber.Ctx) error {
c.Location("http://example.com")
c.Location("/foo/bar")
return nil
})
Method
요청의 HTTP 메서드에 해당하는 문자열을 반환합니다: GET
, POST
, PUT
등.
선택적으로 문자열을 전달하여 메서드를 재정의할 수 있습니다.
Copy func (c *Ctx) Method(override ...string) string
Copy app.Post("/", func(c *fiber.Ctx) error {
c.Method() // "POST"
c.Method("GET")
c.Method() // GET
// ...
})
MultipartForm
MultipartForm()
을 사용하여 바이너리를 파싱하여 multipart 폼 항목에 액세스할 수 있습니다. 이렇게 하면 map[string][]string
이 반환되므로 키가 주어지면 값이 문자열 슬라이스가 됩니다.
Copy func (c *Ctx) MultipartForm() (*multipart.Form, error)
Copy app.Post("/", func(c *fiber.Ctx) error {
// multipart 폼 파싱:
if form, err := c.MultipartForm(); err == nil {
// => *multipart.Form
if token := form.Value["token"]; len(token) > 0 {
// 키 값 가져오기:
fmt.Println(token[0])
}
// "documents" 키에서 모든 파일 가져오기:
files := form.File["documents"]
// => []*multipart.FileHeader
// 파일 루프:
for _, file := range files {
fmt.Println(file.Filename, file.Size, file.Header["Content-Type"][0])
// => "tutorial.pdf" 360641 "application/pdf"
// 파일을 디스크에 저장:
if err := c.SaveFile(file, fmt.Sprintf("./%s", file.Filename)); err != nil {
return err
}
}
}
return err
})
Next
Next 가 호출되면 현재 경로와 일치하는 스택의 다음 메서드를 실행합니다. 메서드 내에서 체이닝을 종료하고 error handler 를 호출하는 error 구조체를 전달할 수 있습니다.
Copy func (c *Ctx) Next() error
Copy app.Get("/", func(c *fiber.Ctx) error {
fmt.Println("1st route!")
return c.Next()
})
app.Get("*", func(c *fiber.Ctx) error {
fmt.Println("2nd route!")
return c.Next()
})
app.Get("/", func(c *fiber.Ctx) error {
fmt.Println("3rd route!")
return c.SendString("Hello, World!")
})
OriginalURL
원래 요청 URL을 반환합니다.
Copy func (c *Ctx) OriginalURL() string
Copy // GET http://example.com/search?q=something
app.Get("/", func(c *fiber.Ctx) error {
c.OriginalURL() // "/search?q=something"
// ...
})
반환된 값은 핸들러 내에서만 유효합니다. 참조를 저장하지 마세요. 복사본을 만들거나 대신 Immutable
설정을 사용하세요. 더 읽기...
Params
경로 매개변수를 가져오는 데 사용할 수 있는 메서드로, param key가 존재하지 않는 경우 반환될 선택적 기본값을 전달할 수 있습니다.
param이 존재하지 않으면 빈 문자열(""
)로 기본 설정됩니다.
Copy func (c *Ctx) Params(key string, defaultValue ...string) string
Copy // GET http://example.com/user/fenny
app.Get("/user/:name", func(c *fiber.Ctx) error {
c.Params("name") // "fenny"
// ...
})
// GET http://example.com/user/fenny/123
app.Get("/user/*", func(c *fiber.Ctx) error {
c.Params("*") // "fenny/123"
c.Params("*1") // "fenny/123"
// ...
})
이름이 없는 경로 매개변수(*, +)는 경로에서 문자 와 카운터 로 가져올 수 있습니다.
Copy // ROUTE: /v1/*/shop/*
// GET: /v1/brand/4/shop/blue/xs
c.Params("*1") // "brand/4"
c.Params("*2") // "blue/xs"
하위 호환성 을 위해 매개변수 문자에 대한 첫 번째 매개변수 세그먼트도 카운터 없이 액세스할 수 있습니다.
Copy app.Get("/v1/*/shop/*", func(c *fiber.Ctx) error {
c.Params("*") // 첫 번째 와일드카드 세그먼트의 값을 출력합니다
})
반환된 값은 핸들러 내에서만 유효합니다. 참조를 저장하지 마세요. 복사본을 만들거나 대신 Immutable
설정을 사용하세요. 더 읽기...
특정 시나리오에서는 문자열뿐만 아니라 다른 유형의 매개변수를 처리하기 위한 대체 접근 방식이 유용할 수 있습니다. 이는 Params[V GenericType](c *Ctx, key string, defaultValue ...V) V
로 알려진 제네릭 Query 함수를 사용하여 달성할 수 있습니다. 이 함수는 V GenericType
으로 가정하고 지정한 유형의 값을 반환하여 쿼리 문자열을 구문 분석할 수 있습니다.
Copy func Params[v GenericType](c *Ctx, key string, default value ...V) V
Copy
// Get http://example.com/user/114
app.Get("/user/:id", func(c *fiber.Ctx) error{
fiber.Params[string](c, "id") // "114"를 문자열로 반환합니다.
fiber.Params[int](c, "id") // 114를 정수로 반환합니다.
fiber.Params[string](c, "number") // ""를 반환합니다(기본 문자열 유형).
fiber.Params[int](c, "number") // 0을 반환합니다(기본 정수 값 유형).
})
제네릭 Params 함수는 V GenericType에 따라 다음 데이터 유형 반환을 지원합니다:
정수: int, int8, int16, int32, int64
부호 없는 정수: uint, uint8, uint16, uint32, uint64
부동 소수점 숫자: float32, float64
Path
요청 URL의 경로 부분을 포함합니다. 선택적으로 문자열을 전달하여 경로를 재정의할 수 있습니다. 내부 리디렉션의 경우 Next 대신 RestartRouting을 호출하는 것이 좋습니다.
Copy func (c *Ctx) Path(override ...string) string
Copy // GET http://example.com/users?sort=desc
app.Get("/users", func(c *fiber.Ctx) error {
c.Path() // "/users"
c.Path("/john")
c.Path() // "/john"
// ...
})
Port
요청의 원격 포트를 반환합니다.
Copy func (c *Ctx) Port() string
Copy // GET http://example.com:8080
app.Get("/", func(c *fiber.Ctx) error {
c.Port() // "8080"
// ...
})
Protocol
요청 프로토콜 문자열을 포함합니다: TLS 요청의 경우 http
또는 https
.
Copy func (c *Ctx) Protocol() string
Copy // GET http://example.com
app.Get("/", func(c *fiber.Ctx) error {
c.Protocol() // "http"
// ...
})
Queries
Queries는 경로의 각 쿼리 문자열 매개변수에 대한 속성을 포함하는 객체를 반환하는 함수입니다.
Copy func (c *Ctx) Queries() map[string]string
Copy // GET http://example.com/?name=alex&want_pizza=false&id=
app.Get("/", func(c *fiber.Ctx) error {
m := c.Queries()
m["name"] // "alex"
m["want_pizza"] // "false"
m["id"] // ""
// ...
})
Copy // GET http://example.com/?field1=value1&field1=value2&field2=value3
app.Get("/", func (c *fiber.Ctx) error {
m := c.Queries()
m["field1"] // "value2"
m["field2"] // value3
})
Copy // GET http://example.com/?list_a=1&list_a=2&list_a=3&list_b[]=1&list_b[]=2&list_b[]=3&list_c=1,2,3
app.Get("/", func(c *fiber.Ctx) error {
m := c.Queries()
m["list_a"] // "3"
m["list_b[]"] // "3"
m["list_c"] // "1,2,3"
})
Copy // GET /api/posts?filters.author.name=John&filters.category.name=Technology
app.Get("/", func(c *fiber.Ctx) error {
m := c.Queries()
m["filters.author.name"] // John
m["filters.category.name"] // Technology
})
Copy // GET /api/posts?tags=apple,orange,banana&filters[tags]=apple,orange,banana&filters[category][name]=fruits&filters.tags=apple,orange,banana&filters.category.name=fruits
app.Get("/", func(c *fiber.Ctx) error {
m := c.Queries()
m["tags"] // apple,orange,banana
m["filters[tags]"] // apple,orange,banana
m["filters[category][name]"] // fruits
m["filters.tags"] // apple,orange,banana
m["filters.category.name"] // fruits
})
Query
이 속성은 경로의 각 쿼리 문자열 매개변수에 대한 속성을 포함하는 객체로, 쿼리 키가 존재하지 않는 경우 반환될 선택적 기본값을 전달할 수 있습니다.
쿼리 문자열이 없으면 빈 문자열 을 반환합니다.
Copy func (c *Ctx) Query(key string, defaultValue ...string) string
Copy // GET http://example.com/?order=desc&brand=nike
app.Get("/", func(c *fiber.Ctx) error {
c.Query("order") // "desc"
c.Query("brand") // "nike"
c.Query("empty", "nike") // "nike"
// ...
})
반환된 값은 핸들러 내에서만 유효합니다. 참조를 저장하지 마세요. 복사본을 만들거나 대신 Immutable
설정을 사용하세요. 더 읽기...
특정 시나리오에서는 문자열뿐만 아니라 다른 유형의 쿼리 매개변수를 처리하기 위한 대체 접근 방식이 유용할 수 있습니다. 이는 Query[V GenericType](c *Ctx, key string, defaultValue ...V) V
로 알려진 제네릭 Query 함수를 사용하여 달성할 수 있습니다. 이 함수는 쿼리 문자열을 파싱하고 V GenericType
에 의해 가정되고 지정된 유형의 값을 반환할 수 있습니다.
제네릭 Query 함수의 시그니처는 다음과 같습니다:
Copy func Query[V GenericType](c *Ctx, key string, defaultValue ...V) V
이 예제를 고려해 보세요:
Copy // GET http://example.com/?page=1&brand=nike&new=true
app.Get("/", func(c *fiber.Ctx) error {
fiber.Query[int](c, "page") // 1
fiber.Query[string](c, "brand") // "nike"
fiber.Query[bool](c, "new") // true
// ...
})
이 경우 Query[V GenericType](c *Ctx, key string, defaultValue ...V) V
는 'page'를 정수로, 'brand'를 문자열로, 'new'를 부울로 검색할 수 있습니다. 이 함수는 지정된 각 유형에 적합한 파싱 함수를 사용하여 올바른 유형이 반환되도록 합니다. 이렇게 하면 다른 유형의 쿼리 매개변수 검색 프로세스가 단순화되어 컨트롤러 액션이 더 깔끔해집니다.
제네릭 Query 함수는 V GenericType에 따라 다음 데이터 유형 반환을 지원합니다:
정수: int, int8, int16, int32, int64
부호 없는 정수: uint, uint8, uint16, uint32, uint64
부동 소수점 숫자: float32, float64
Range
유형과 범위 슬라이스를 포함하는 구조체가 반환됩니다.
Copy func (c *Ctx) Range(size int) (Range, error)
Copy // Range: bytes=500-700, 700-900
app.Get("/", func(c *fiber.Ctx) error {
b := c.Range(1000)
if b.Type == "bytes" {
for r := range r.Ranges {
fmt.Println(r)
// [500, 700]
}
}
})
Redirect
리디렉션 참조를 반환합니다.
자세한 내용은 Redirect 문서를 참조하세요.
Copy func (c *Ctx) Redirect() *Redirect
Copy app.Get("/coffee", func(c *fiber.Ctx) error {
return c.Redirect().To("/teapot")
})
app.Get("/teapot", func(c *fiber.Ctx) error {
return c.Status(fiber.StatusTeapot).Send("🍵 short and stout 🍵")
})
Render
데이터로 뷰를 렌더링하고 text/html
응답을 보냅니다. 기본적으로 Render
는 기본 Go 템플릿 엔진 을 사용합니다. 다른 뷰 엔진을 사용하려면 템플릿 미들웨어 를 살펴보세요.
Copy func (c *Ctx) Render(name string, bind Map, layouts ...string) error
Request
*fasthttp.Request 포인터를 반환합니다.
Copy func (c *Ctx) Request() *fasthttp.Request
Copy app.Get("/", func(c *fiber.Ctx) error {
c.Request().Header.Method()
// => []byte("GET")
})
Response
*fasthttp.Response 포인터를 반환합니다.
Copy func (c *Ctx) Response() *fasthttp.Response
Copy app.Get("/", func(c *fiber.Ctx) error {
c.Response().BodyWriter().Write([]byte("Hello, World!"))
// => "Hello, World!"
return nil
})
Reset
서버 핸들러를 사용할 때 주어진 요청으로 컨텍스트 필드를 재설정합니다.
Copy func (c *Ctx) Reset(*fasthttp.RequestCtx)
Fiber 핸들러 외부에서 다음 요청에 대한 컨텍스트를 재설정하는 데 사용됩니다.
RestartRouting
Next를 호출할 때 다음 메서드를 실행하는 대신 RestartRouting 은 현재 경로와 일치하는 첫 번째 메서드에서 실행을 다시 시작합니다. 이는 경로를 재정의한 후에 도움이 될 수 있습니다(예: 내부 리디렉션). 핸들러가 다시 실행될 수 있으므로 무한 루프가 발생할 수 있습니다.
Copy func (c *Ctx) RestartRouting() error
Copy app.Get("/new", func(c *fiber.Ctx) error {
return c.SendString("From /new")
})
app.Get("/old", func(c *fiber.Ctx) error {
c.Path("/new")
return c.RestartRouting()
})
Route
일치하는 Route 구조체를 반환합니다.
Copy func (c *Ctx) Route() *Route
Copy // http://localhost:8080/hello
app.Get("/hello/:name", func(c *fiber.Ctx) error {
r := c.Route()
fmt.Println(r.Method, r.Path, r.Params, r.Handlers)
// GET /hello/:name handler [name]
// ...
})
c.Next()
를 호출하기 전에 미들웨어에서 c.Route()
에 의존하지 마세요 - c.Route()
는 마지막으로 실행된 경로 를 반환합니다.
Copy func MyMiddleware() fiber.Handler {
return func(c *fiber.Ctx) error {
beforeNext := c.Route().Path // '/'가 될 것입니다
err := c.Next()
afterNext := c.Route().Path // '/hello/:name'이 될 것입니다
return err
}
}
SaveFile
모든 multipart 파일을 디스크에 저장하는 데 사용되는 메서드입니다.
Copy func (c *Ctx) SaveFile(fh *multipart.FileHeader, path string) error
Copy app.Post("/", func(c *fiber.Ctx) error {
// multipart 폼 파싱:
if form, err := c.MultipartForm(); err == nil {
// => *multipart.Form
// "documents" 키에서 모든 파일 가져오기:
files := form.File["documents"]
// => []*multipart.FileHeader
// 파일 루프:
for _, file := range files {
fmt.Println(file.Filename, file.Size, file.Header["Content-Type"][0])
// => "tutorial.pdf" 360641 "application/pdf"
// 파일을 디스크에 저장:
if err := c.SaveFile(file, fmt.Sprintf("./%s", file.Filename)); err != nil {
return err
}
}
return err
}
})
SaveFileToStorage
모든 multipart 파일을 외부 스토리지 시스템에 저장하는 데 사용되는 메서드입니다.
Copy func (c *Ctx) SaveFileToStorage(fileheader *multipart.FileHeader, path string, storage Storage) error
Copy storage := memory.New()
app.Post("/", func(c *fiber.Ctx) error {
// multipart 폼 파싱:
if form, err := c.MultipartForm(); err == nil {
// => *multipart.Form
// "documents" 키에서 모든 파일 가져오기:
files := form.File["documents"]
// => []*multipart.FileHeader
// 파일 루프:
for _, file := range files {
fmt.Println(file.Filename, file.Size, file.Header["Content-Type"][0])
// => "tutorial.pdf" 360641 "application/pdf"
// 파일을 스토리지에 저장:
if err := c.SaveFileToStorage(file, fmt.Sprintf("./%s", file.Filename), storage); err != nil {
return err
}
}
return err
}
})
Schema
TLS 요청의 경우 요청 프로토콜 문자열: http 또는 https를 포함합니다.
앱이 프록시 뒤에 있는 경우 헤더 스푸핑을 방지하려면 Config.EnableTrustedProxyCheck
를 사용하세요.
Copy func (c *Ctx) Schema() string
Copy // GET http://example.com
app.Get("/", func(c *fiber.Ctx) error {
c.Schema() // "http"
// ...
})
Secure
TLS 연결이 설정되면 true
인 부울 속성입니다.
Copy func (c *Ctx) Secure() bool
Copy // Secure() 메서드는 다음과 동일합니다:
c.Protocol() == "https"
Send
HTTP 응답 본문을 설정합니다.
Copy func (c *Ctx) Send(body []byte) error
Copy app.Get("/", func(c *fiber.Ctx) error {
return c.Send([]byte("Hello, World!")) // => "Hello, World!"
})
원시 입력을 위해 SendString
및 SendStream
메서드도 제공합니다.
더 빠른 성능을 위해 타입 어설션이 필요하지 않은 경우 이를 사용하세요.
Copy func (c *Ctx) SendString(body string) error
func (c *Ctx) SendStream(stream io.Reader, size ...int) error
Copy app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, World!")
// => "Hello, World!"
return c.SendStream(bytes.NewReader([]byte("Hello, World!")))
// => "Hello, World!"
})
SendFile
주어진 경로에서 파일을 전송합니다. 파일 이름 확장자를 기반으로 Content-Type 응답 HTTP 헤더 필드를 설정합니다.
메서드는 기본적으로 gzipping 을 사용하지 않습니다. 활성화하려면 true 로 설정하세요.
Copy func (c *Ctx) SendFile(file string, compress ...bool) error
Copy app.Get("/not-found", func(c *fiber.Ctx) error {
return c.SendFile("./public/404.html");
// 압축 비활성화
return c.SendFile("./static/index.html", false);
})
파일에 URL 특정 문자가 포함된 경우 sendFile
함수에 파일 경로를 전달하기 전에 이스케이프해야 합니다.
Copy app.Get("/file-with-url-chars", func(c *fiber.Ctx) error {
return c.SendFile(url.PathEscape("hash_sign_#.txt"))
})
임베디드 파일 시스템에서 파일을 보내려면 이 기능을 사용할 수 있습니다.
SendStatus
상태 코드를 설정하고 응답 본문이 비어 있는 경우 본문에 올바른 상태 메시지를 설정합니다.
사용된 모든 상태 코드와 메시지는 여기 에서 찾을 수 있습니다.
Copy func (c *Ctx) SendStatus(status int) error
Copy app.Get("/not-found", func(c *fiber.Ctx) error {
return c.SendStatus(415)
// => 415 "Unsupported Media Type"
c.SendString("Hello, World!")
return c.SendStatus(415)
// => 415 "Hello, World!"
})
SendStream
응답 본문을 데이터 스트림으로 설정하고 선택적으로 본문 크기를 추가합니다.
Copy func (c *Ctx) SendStream(stream io.Reader, size ...int) error
Copy app.Get("/", func(c *fiber.Ctx) error {
return c.SendStream(bytes.NewReader([]byte("Hello, World!")))
// => "Hello, World!"
})
SendString
응답 본문을 문자열로 설정합니다.
Copy func (c *Ctx) SendString(body string) error
Copy app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, World!")
// => "Hello, World!"
})
Set
응답의 HTTP 헤더 필드를 지정된 key
, value
로 설정합니다.
Copy func (c *Ctx) Set(key string, val string)
Copy app.Get("/", func(c *fiber.Ctx) error {
c.Set("Content-Type", "text/plain")
// => "Content-type: text/plain"
// ...
})
SetUserContext
컨텍스트 인터페이스에 대해 사용자가 지정한 구현을 설정합니다.
Copy func (c *Ctx) SetUserContext(ctx context.Context)
Copy app.Get("/", func(c *fiber.Ctx) error {
ctx := context.Background()
c.SetUserContext(ctx)
// 여기서 ctx는 모든 컨텍스트 구현일 수 있습니다
// ...
})
Stale
https://expressjs.com/en/4x/api.html#req.stale
Copy func (c *Ctx) Stale() bool
Status
응답에 대한 HTTP 상태를 설정합니다.
Copy func (c *Ctx) Status(status int) Ctx
Copy app.Get("/fiber", func(c *fiber.Ctx) error {
c.Status(fiber.StatusOK)
return nil
}
app.Get("/hello", func(c *fiber.Ctx) error {
return c.Status(fiber.StatusBadRequest).SendString("Bad Request")
}
app.Get("/world", func(c *fiber.Ctx) error {
return c.Status(fiber.StatusNotFound).SendFile("./public/gopher.png")
})
String
ctx의 고유한 문자열 표현을 반환합니다.
Copy func (c *Ctx) String() string
Copy app.Get("/", func(c *fiber.Ctx) error {
c.String() // => "#0000000100000001 - 127.0.0.1:3000 <-> 127.0.0.1:61516 - GET http://localhost:3000/"
// ...
})
Subdomains
요청의 도메인 이름에서 하위 도메인의 문자열 슬라이스를 반환합니다.
2
로 기본 설정되는 애플리케이션 속성 하위 도메인 오프셋은 하위 도메인 세그먼트의 시작을 결정하는 데 사용됩니다.
Copy func (c *Ctx) Subdomains(offset ...int) []string
Copy // Host: "tobi.ferrets.example.com"
app.Get("/", func(c *fiber.Ctx) error {
c.Subdomains() // ["ferrets", "tobi"]
c.Subdomains(1) // ["tobi"]
// ...
})
Type
파일 extension 으로 지정된 여기 에 나열된 MIME 유형으로 Content-Type HTTP 헤더를 설정합니다.
Copy func (c *Ctx) Type(ext string, charset ...string) Ctx
Copy app.Get("/", func(c *fiber.Ctx) error {
c.Type(".html") // => "text/html"
c.Type("html") // => "text/html"
c.Type("png") // => "image/png"
c.Type("json", "utf-8") // => "application/json; charset=utf-8"
// ...
})
UserContext
사용자가 이전에 설정한 컨텍스트 구현을 반환하거나, 설정되지 않은 경우 비어 있지 않은 컨텍스트를 반환합니다.
Copy func (c *Ctx) UserContext() context.Context
Copy app.Get("/", func(c *fiber.Ctx) error {
ctx := c.UserContext()
// ctx는 사용자가 설정한 컨텍스트 구현입니다
// ...
})
Vary
주어진 헤더 필드를 Vary 응답 헤더에 추가합니다. 아직 나열되지 않은 경우 헤더를 추가하고, 그렇지 않으면 현재 위치에 나열된 상태로 둡니다.
Copy func (c *Ctx) Vary(fields ...string)
Copy app.Get("/", func(c *fiber.Ctx) error {
c.Vary("Origin") // => Vary: Origin
c.Vary("User-Agent") // => Vary: Origin, User-Agent
// 중복 없음
c.Vary("Origin") // => Vary: Origin, User-Agent
c.Vary("Accept-Encoding", "Accept")
// => Vary: Origin, User-Agent, Accept-Encoding, Accept
// ...
})
ViewBind
템플릿 엔진에 바인딩할 기본 뷰 변수 맵에 변수를 추가합니다. 변수는 Render 메서드에 의해 읽혀지며 덮어쓰일 수 있습니다.
Copy func (c *Ctx) ViewBind(vars fiber.Map) error
Copy app.Use(func(c *fiber.Ctx) error {
c.ViewBind(fiber.Map{
"Title": "Hello, World!",
})
})
app.Get("/", func(c *fiber.Ctx) error {
return c.Render("xxx.tmpl", fiber.Map{}) // Render는 Title 변수를 사용할 것입니다
})
Write
Writer 인터페이스를 채택합니다.
Copy func (c *Ctx) Write(p []byte) (n int, err error)
Copy app.Get("/", func(c *fiber.Ctx) error {
c.Write([]byte("Hello, World!")) // => "Hello, World!"
fmt.Fprintf(c, "%s\n", "Hello, World!") // "Hello, World!Hello, World!"
})
Writef
변수가 있는 문자열을 채택합니다.
Copy func (c *Ctx) Writef(f string, a ...any) (n int, err error)
Copy app.Get("/", func(c *fiber.Ctx) error {
world := "World!"
c.Writef("Hello, %s", world) // => "Hello, World!"
fmt.Fprintf(c, "%s\n", "Hello, World!") // "Hello, World!Hello, World!"
})
WriteString
문자열을 채택합니다.
Copy func (c *Ctx) WriteString(s string) (n int, err error)
Copy app.Get("/", func(c *fiber.Ctx) error {
c.WriteString("Hello, World!") // => "Hello, World!"
fmt.Fprintf(c, "%s\n", "Hello, World!") // "Hello, World!Hello, World!"
})
XHR
요청의 X-Requested-With 헤더 필드가 XMLHttpRequest 인 경우 true
인 부울 속성으로, 요청이 jQuery 와 같은 클라이언트 라이브러리에 의해 발행되었음을 나타냅니다.
Copy func (c *Ctx) XHR() bool
Copy // X-Requested-With: XMLHttpRequest
app.Get("/", func(c *fiber.Ctx) error {
c.XHR() // true
// ...
})
XML
표준 encoding/xml
패키지를 사용하여 interface 또는 string 을 XML로 변환합니다.
XML은 콘텐츠 헤더를 application/xml 로 설정합니다.
Copy func (c *Ctx) XML(data interface{}) error
Copy type SomeStruct struct {
XMLName xml.Name `xml:"Fiber"`
Name string `xml:"Name"`
Age uint8 `xml:"Age"`
}
app.Get("/", func(c *fiber.Ctx) error {
// 데이터 구조체 생성:
data := SomeStruct{
Name: "Grame",
Age: 20,
}
return c.XML(data)
// <Fiber>
// <Name>Grame</Name>
// <Age>20</Age>
// </Fiber>
})