Static
Static 메서드를 사용하여 이미지, CSS, JavaScript와 같은 정적 파일을 제공합니다.
기본적으로 Static은 디렉토리에 대한 요청에 대해 index.html
파일을 제공합니다.
func (app *App) Static(prefix, root string, config ...Static) Router
./public
디렉토리에 있는 파일을 제공하려면 다음 코드를 사용하세요.
// 여러 디렉토리에서 파일 제공
app.Static("/", "./public")
// => http://localhost:3000/hello.html
// => http://localhost:3000/js/jquery.js
// => http://localhost:3000/css/style.css
// "./files" 디렉토리에서 파일 제공:
app.Static("/", "./files")
Static 메서드로 제공되는 파일에 대해 가상 경로 접두사(실제로 파일 시스템에 존재하지 않는 경로)를 사용할 수 있습니다. 아래와 같이 정적 디렉토리에 대한 접두사 경로를 지정하세요:
app.Static("/static", "./public")
// => http://localhost:3000/static/hello.html
// => http://localhost:3000/static/js/jquery.js
// => http://localhost:3000/static/css/style.css
Config
정적 파일 제공에 대한 설정을 좀 더 제어하고 싶다면 fiber.Static
구조체를 사용하여 특정 설정을 활성화할 수 있습니다.
Property
Type
Description
Default
true로 설정하면 압축된 파일을 캐싱하여 CPU 사용량을 최소화하려고 합니다. 이는 compress 미들웨어와 다르게 작동합니다.
true로 설정하면 바이트 범위 요청을 활성화합니다.
true로 설정하면 디렉토리 탐색을 활성화합니다.
true로 설정하면 직접 다운로드를 활성화합니다.
디렉토리 제공을 위한 색인 파일의 이름입니다.
비활성 파일 핸들러의 만료 기간입니다. 비활성화하려면 음수 time.Duration
을 사용하세요.
파일 응답에 설정되는 Cache-Control
HTTP 헤더의 값입니다. MaxAge는 초 단위로 정의됩니다.
ModifyResponse는 응답을 변경할 수 있는 함수를 정의합니다.
Next는 true를 반환하면 이 미들웨어를 건너뛰는 함수를 정의합니다.
// 사용자 정의 설정
app.Static("/", "./public", fiber.Static{
Compress: true,
ByteRange: true,
Browse: true,
Index: "john.html",
CacheDuration: 10 * time.Second,
MaxAge: 3600,
})
Route Handlers
Mounting
express
와 유사하게 app.Use
메서드를 사용하여 Fiber 인스턴스를 마운트할 수 있습니다.
func main() {
app := fiber.New()
micro := fiber.New()
app.Use("/john", micro) // GET /john/doe -> 200 OK
micro.Get("/doe", func(c fiber.Ctx) error {
return c.SendStatus(fiber.StatusOK)
})
log.Fatal(app.Listen(":3000"))
}
MountPath
MountPath
속성에는 하위 앱이 마운트된 하나 이상의 경로 패턴이 포함되어 있습니다.
func (app *App) MountPath() string
func main() {
app := fiber.New()
one := fiber.New()
two := fiber.New()
three := fiber.New()
two.Use("/three", three)
one.Use("/two", two)
app.Use("/one", one)
one.MountPath() // "/one"
two.MountPath() // "/one/two"
three.MountPath() // "/one/two/three"
app.MountPath() // ""
}
MountPath의 경우 마운팅 순서가 중요합니다. 마운트 경로를 제대로 가져오려면 가장 깊은 앱부터 마운팅을 시작해야 합니다.내용
Group
*Group
구조체를 생성하여 라우트를 그룹화할 수 있습니다.
func (app *App) Group(prefix string, handlers ...Handler) Router
func main() {
app := fiber.New()
api := app.Group("/api", handler) // /api
v1 := api.Group("/v1", handler) // /api/v1
v1.Get("/list", handler) // /api/v1/list
v1.Get("/user", handler) // /api/v1/user
v2 := api.Group("/v2", handler) // /api/v2
v2.Get("/list", handler) // /api/v2/list
v2.Get("/user", handler) // /api/v2/user
log.Fatal(app.Listen(":3000"))
}
Route
공통 함수 내에서 공통 접두사를 가진 라우트를 정의할 수 있습니다.
func (app *App) Route(prefix string, fn func(router Router), name ...string) Router
func main() {
app := fiber.New()
app.Route("/test", func(api fiber.Router) {
api.Get("/foo", handler).Name("foo") // /test/foo (name: test.foo)
api.Get("/bar", handler).Name("bar") // /test/bar (name: test.bar)
}, "test.")
log.Fatal(app.Listen(":3000"))
}
HandlersCount
이 메서드는 등록된 핸들러의 수를 반환합니다.
func (app *App) HandlersCount() uint32
Stack
이 메서드는 원래의 라우터 스택을 반환합니다.
func (app *App) Stack() [][]*Route
var handler = func(c fiber.Ctx) error { return nil }
func main() {
app := fiber.New()
app.Get("/john/:age", handler)
app.Post("/register", handler)
data, _ := json.MarshalIndent(app.Stack(), "", " ")
fmt.Println(string(data))
app.Listen(":3000")
}
결과를 보려면 여기를 클릭하세요
[
[
{
"method": "GET",
"path": "/john/:age",
"params": [
"age"
]
}
],
[
{
"method": "HEAD",
"path": "/john/:age",
"params": [
"age"
]
}
],
[
{
"method": "POST",
"path": "/register",
"params": null
}
]
]
Name
이 메서드는 가장 최근에 생성된 라우트의 이름을 할당합니다.
func (app *App) Name(name string) Router
var handler = func(c fiber.Ctx) error { return nil }
func main() {
app := fiber.New()
app.Get("/", handler)
app.Name("index")
app.Get("/doe", handler).Name("home")
app.Trace("/tracer", handler).Name("tracert")
app.Delete("/delete", handler).Name("delete")
a := app.Group("/a")
a.Name("fd.")
a.Get("/test", handler).Name("test")
data, _ := json.MarshalIndent(app.Stack(), "", " ")
fmt.Print(string(data))
app.Listen(":3000")
}
결과를 보려면 여기를 클릭하세요
[
[
{
"method": "GET",
"name": "index",
"path": "/",
"params": null
},
{
"method": "GET",
"name": "home",
"path": "/doe",
"params": null
},
{
"method": "GET",
"name": "fd.test",
"path": "/a/test",
"params": null
}
],
[
{
"method": "HEAD",
"name": "",
"path": "/",
"params": null
},
{
"method": "HEAD",
"name": "",
"path": "/doe",
"params": null
},
{
"method": "HEAD",
"name": "",
"path": "/a/test",
"params": null
}
],
null,
null,
[
{
"method": "DELETE",
"name": "delete",
"path": "/delete",
"params": null
}
],
null,
null,
[
{
"method": "TRACE",
"name": "tracert",
"path": "/tracer",
"params": null
}
],
null
]
GetRoute
이 메서드는 이름으로 라우트를 가져옵니다.
func (app *App) GetRoute(name string) Route
var handler = func(c fiber.Ctx) error { return nil }
func main() {
app := fiber.New()
app.Get("/", handler).Name("index")
data, _ := json.MarshalIndent(app.GetRoute("index"), "", " ")
fmt.Print(string(data))
app.Listen(":3000")
}
결과를 보려면 여기를 클릭하세요
{
"method": "GET",
"name": "index",
"path": "/",
"params": null
}
GetRoutes
이 메서드는 모든 라우트를 가져옵니다.
func (app *App) GetRoutes(filterUseOption ...bool) []Route
filterUseOption이 true일 때 미들웨어에 의해 등록된 라우트는 필터링됩니다.
func main() {
app := fiber.New()
app.Post("/", func (c fiber.Ctx) error {
return c.SendString("Hello, World!")
}).Name("index")
data, _ := json.MarshalIndent(app.GetRoutes(true), "", " ")
fmt.Print(string(data))
}
결과를 보려면 여기를 클릭하세요
[
{
"method": "POST",
"name": "index",
"path": "/",
"params": null
}
]
Config
Config는 값으로 앱 설정을 반환합니다(읽기 전용).
func (app *App) Config() Config
Handler
Handler는 사용자 정의 \*fasthttp.RequestCtx
요청을 제공하는 데 사용할 수 있는 서버 핸들러를 반환합니다.
func (app *App) Handler() fasthttp.RequestHandler
ErrorHandler
Errorhandler는 오류가 발생한 경우 애플리케이션에 대해 정의된 프로세스를 실행합니다. 이는 일부 미들웨어에서 사용됩니다.
func (app *App) ErrorHandler(ctx Ctx, err error) error
NewCtxFunc
NewCtxFunc를 사용하면 원하는 대로 ctx 구조체를 사용자 정의할 수 있습니다.
func (app *App) NewCtxFunc(function func(app *App) CustomCtx)
type CustomCtx struct {
DefaultCtx
}
// 사용자 정의 메서드
func (c *CustomCtx) Params(key string, defaultValue ...string) string {
return "prefix_" + c.DefaultCtx.Params(key)
}
app := New()
app.NewCtxFunc(func(app *fiber.App) fiber.CustomCtx {
return &CustomCtx{
DefaultCtx: *NewDefaultCtx(app),
}
})
// curl http://localhost:3000/123
app.Get("/:id", func(c Ctx) error {
// 사용자 정의 메서드 사용 - 출력: prefix_123
return c.SendString(c.Params("id"))
})
RegisterCustomBinder
CustomBinder 인터페이스와 호환되는 사용자 정의 바인더를 등록할 수 있습니다.
func (app *App) RegisterCustomBinder(binder CustomBinder)
app := fiber.New()
// 사용자 정의 바인더
customBinder := &customBinder{}
// 사용자 정의 바인더의 이름, Bind().Custom("name")으로 사용됨
func (*customBinder) Name() string {
return "custom"
}
// 바인더가 사용자 정의 mime 유형에 사용되어야 하는지 확인하기 위해 Body Bind 메서드에서 사용됨
func (*customBinder) MIMETypes() []string {
return []string{"application/yaml"}
}
// 본문을 구문 분석하고 인터페이스에 바인딩
func (*customBinder) Parse(c Ctx, out any) error {
// yaml 본문 구문 분석
return yaml.Unmarshal(c.Body(), out)
}
// 사용자 정의 바인더 등록
app.RegisterCustomBinder(customBinder)
// curl -X POST http://localhost:3000/custom -H "Content-Type: application/yaml" -d "name: John"
app.Post("/custom", func(c Ctx) error {
var user User
// 출력: {Name:John}
// 사용자 정의 바인더는 이름으로 사용됨
if err := c.Bind().Custom("custom", &user); err != nil {
return err
}
// ...
return c.JSON(user)
})
// curl -X POST http://localhost:3000/normal -H "Content-Type: application/yaml" -d "name: Doe"
app.Post("/normal", func(c Ctx) error {
var user User
// 출력: {Name:Doe}
// 사용자 정의 바인더는 mime 유형으로 사용됨
if err := c.Bind().Body(&user); err != nil {
return err
}
// ...
return c.JSON(user)
})
RegisterCustomConstraint
RegisterCustomConstraint를 사용하면 사용자 정의 제약 조건을 등록할 수 있습니다.
func (app *App) RegisterCustomConstraint(constraint CustomConstraint)
자세한 내용은 사용자 정의 제약 조건 섹션을 참조하세요.
SetTLSHandler
Listener와 함께 TLS를 사용할 때 ClientHelloInfo를 설정하려면 SetTLSHandler를 사용하세요.
func (app *App) SetTLSHandler(tlsHandler *TLSHandler)
Test
애플리케이션 테스트는 Test 메서드로 수행됩니다. _test.go
파일을 생성할 때나 라우팅 로직을 디버깅해야 할 때 이 메서드를 사용하세요. 기본 제한 시간은 1s
이며 제한 시간을 완전히 비활성화하려면 두 번째 인수로 -1
을 전달하세요.
func (app *App) Test(req *http.Request, msTimeout ...int) (*http.Response, error)
// 테스트를 위해 GET 메서드로 라우트 생성:
app.Get("/", func(c fiber.Ctx) error {
fmt.Println(c.BaseURL()) // => http://google.com
fmt.Println(c.Get("X-Custom-Header")) // => hi
return c.SendString("hello, World!")
})
// http.Request
req := httptest.NewRequest("GET", "http://google.com", nil)
req.Header.Set("X-Custom-Header", "hi")
// http.Response
resp, _ := app.Test(req)
// 결과 처리:
if resp.StatusCode == fiber.StatusOK {
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body)) // => Hello, World!
}
Hooks
Hooks는 hooks 속성을 반환하는 메서드입니다.
func (app *App) Hooks() *Hooks
Last updated