이 장에서는 Go Fiber가 요청과 응답을 처리하는 방법을 소개하며, 일반적으로 현재 API 개발을 위해 JSON 데이터를 반환합니다.
Fiber 프레임워크는 주로 Ctx
컨텍스트 객체의 반환 데이터를 사용합니다.
JSON 데이터 반환
type SomeStruct struct {
Name string
Age uint8
}
app.Get("/json", func(c *fiber.Ctx) error {
// 응답용 데이터 구조 생성
data := SomeStruct{
Name: "Grame",
Age: 20,
}
// json 함수를 사용하여 반환
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}"
})
JSONP 형식 반환
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})
})
텍스트 반환
app.Get("/", func(c *fiber.Ctx) error {
// "Hello, World ?!"를 문자열로 반환
return c.SendString("Hello, World ?!")
})
상태 코드 반환
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!"
})
파일 반환 (파일 다운로드 구현)
app.Get("/", func(c *fiber.Ctx) error {
return c.Download("./files/report-12345.pdf");
// => report-12345.pdf 다운로드
return c.Download("./files/report-12345.pdf", "report.pdf");
// => report.pdf 다운로드
})
요청 헤더 설정
app.Get("/", func(c *fiber.Ctx) error {
c.Set("Content-Type", "text/plain")
// => "Content-type: text/plain"
// ...
})
쿠키 설정
쿠키 정의
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"`
}
쿠키 반환
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)
// ...
})
리다이렉트 (301 또는 302)
기본적으로 302 리다이렉트
app.Get("/", func(c *fiber.Ctx) error {
return c.Redirect("/foo/bar")
return c.Redirect("../login")
return c.Redirect("http://example.com")
return c.Redirect("http://example.com", 301)
})