라우팅은 애플리케이션의 엔드포인트(URIs)가 클라이언트 요청에 응답하는 방식을 말합니다.
Handlers
Signature Example
Copy func(c *fiber.Ctx) error
Copy app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, World 👋!")
})
Paths
Route paths는 request method와 결합되어 요청이 이루어질 수 있는 엔드포인트를 정의합니다. Route paths는 strings 또는 string patterns 일 수 있습니다.
문자열 기반 route paths 예시
Copy // 이 route path는 루트 경로 "/"에 대한 요청과 일치합니다:
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("root")
})
// 이 route path는 "/about"에 대한 요청과 일치합니다:
app.Get("/about", func(c *fiber.Ctx) error {
return c.SendString("about")
})
// 이 route path는 "/random.txt"에 대한 요청과 일치합니다:
app.Get("/random.txt", func(c *fiber.Ctx) error {
return c.SendString("random.txt")
})
expressJs 프레임워크와 같이 route 선언 순서가 중요한 역할을 합니다.
요청이 수신되면 선언된 순서대로 route가 확인됩니다.
Parameters
:, +, *는 parameter를 도입하는 문자입니다.
Greedy parameters는 wildcard(*) 또는 plus(+) 기호로 표시됩니다.
라우팅은 또한 선택적 매개변수를 사용할 가능성을 제공합니다. 명명된 매개변수의 경우 최종 "?"로 표시되는 반면, plus 기호는 선택 사항이 아닙니다. 선택적이고 greedy한 매개변수 범위에 wildcard 문자를 사용할 수 있습니다.
route parameters를 사용하여 route 정의 예시
Copy // Parameters
app.Get("/user/:name/books/:title", func(c *fiber.Ctx) error {
fmt.Fprintf(c, "%s\n", c.Params("name"))
fmt.Fprintf(c, "%s\n", c.Params("title"))
return nil
})
// Plus - greedy - not optional
app.Get("/user/+", func(c *fiber.Ctx) error {
return c.SendString(c.Params("+"))
})
// 선택적 parameter
app.Get("/user/:name?", func(c *fiber.Ctx) error {
return c.SendString(c.Params("name"))
})
// Wildcard - greedy - optional
app.Get("/user/*", func(c *fiber.Ctx) error {
return c.SendString(c.Params("*"))
})
// 이 route path는 parameter 문자가 이스케이프되므로 "/v1/some/resource/name:customVerb"에 대한 요청과 일치합니다.
app.Get(`/v1/some/resource/name\:customVerb`, func(c *fiber.Ctx) error {
return c.SendString("Hello, Community")
})
Copy // http://localhost:3000/plantae/prunus.persica
app.Get("/plantae/:genus.:species", func(c *fiber.Ctx) error {
fmt.Fprintf(c, "%s.%s\n", c.Params("genus"), c.Params("species"))
return nil // prunus.persica
})
Copy // http://localhost:3000/flights/LAX-SFO
app.Get("/flights/:from-:to", func(c *fiber.Ctx) error {
fmt.Fprintf(c, "%s-%s\n", c.Params("from"), c.Params("to"))
return nil // LAX-SFO
})
우리의 지능형 라우터는 이 경우 도입 parameter 문자가 요청 route의 일부여야 한다는 것을 인식하고 그에 따라 처리할 수 있습니다.
Copy // http://localhost:3000/shop/product/color:blue/size:xs
app.Get("/shop/product/color::color/size::size", func(c *fiber.Ctx) error {
fmt.Fprintf(c, "%s:%s\n", c.Params("color"), c.Params("size"))
return nil // blue:xs
})
게다가 연속된 여러 parameter와 wildcard 또는 plus 문자와 같은 route의 여러 이름 없는 parameter 문자가 가능하므로 사용자를 위한 라우터의 가능성을 크게 확장합니다.
Copy // GET /@v1
// Params: "sign" -> "@", "param" -> "v1"
app.Get("/:sign:param", handler)
// GET /api-v1
// Params: "name" -> "v1"
app.Get("/api-:name", handler)
// GET /customer/v1/cart/proxy
// Params: "*1" -> "customer/", "*2" -> "/cart"
app.Get("/*v1*/proxy", handler)
// GET /v1/brand/4/shop/blue/xs
// Params: "*1" -> "brand/4", "*2" -> "blue/xs"
app.Get("/v1/*/shop/*", handler)
Constraints
Constraint
Example
Example matches
CD2C1638-1638-72D5-1638-DEADBEEF1638
91 (정수 값은 최소 18 이상 최대 120 이하여야 함)
Rick (문자열은 하나 이상의 알파벳 문자로 구성되어야 하며, a-z이고 대소문자를 구분하지 않음)
:dob<datetime(2006\\-01\\-02)>
:date<regex(\d{4}-\d{2}-\d{2})>
2022-08-27 (정규 표현식과 일치해야 함)
예제
Single Constraint Multiple Constraints Regex Constraint
Copy app.Get("/:test<min(5)>", func(c *fiber.Ctx) error {
return c.SendString(c.Params("test"))
})
// curl -X GET http://localhost:3000/12
// 12
// curl -X GET http://localhost:3000/1
// Cannot GET /1
여러 constraints에는 ;
를 사용할 수 있습니다.
Copy app.Get("/:test<min(100);maxLen(5)>", func(c *fiber.Ctx) error {
return c.SendString(c.Params("test"))
})
// curl -X GET http://localhost:3000/120000
// Cannot GET /120000
// curl -X GET http://localhost:3000/1
// Cannot GET /1
// curl -X GET http://localhost:3000/250
// 250
Fiber는 route를 등록할 때 regex query를 미리 컴파일합니다. 따라서 regex constraint에 대한 성능 오버헤드는 없습니다.
Copy app.Get(`/:date<regex(\d{4}-\d{2}-\d{2})>`, func(c *fiber.Ctx) error {
return c.SendString(c.Params("date"))
})
// curl -X GET http://localhost:3000/125
// Cannot GET /125
// curl -X GET http://localhost:3000/test
// Cannot GET /test
// curl -X GET http://localhost:3000/2022-08-27
// 2022-08-27
Optional Parameter 예제
선택적 parameters에도 constraints를 부과할 수 있습니다.
Copy app.Get("/:test<int>?", func(c *fiber.Ctx) error {
return c.SendString(c.Params("test"))
})
// curl -X GET http://localhost:3000/42
// 42
// curl -X GET http://localhost:3000/
//
// curl -X GET http://localhost:3000/7.0
// Cannot GET /7.0
Middleware
요청이나 응답을 변경하도록 설계된 함수를 middleware 함수 라고 합니다. Next는 Fiber 라우터 함수로, 호출되면 현재 route와 일치하는 다음 함수를 실행합니다.
middleware 함수 예제
Copy app.Use(func(c *fiber.Ctx) error {
// 모든 응답에 대해 사용자 지정 헤더 설정:
c.Set("X-Custom-Header", "Hello, World")
// 다음 middleware로 이동:
return c.Next()
})
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, World!")
})
Use
메서드 경로는 마운트 또는 접두사 경로이며 middleware가 시작하는 요청된 경로에만 적용되도록 제한합니다.
동적으로 Routes 추가에 대한 제한
Grouping
많은 엔드포인트가 있는 경우 Group
을 사용하여 routes를 구성할 수 있습니다.
Copy func main() {
app := fiber.New()
api := app.Group("/api", middleware) // /api
v1 := api.Group("/v1", middleware) // /api/v1
v1.Get("/list", handler) // /api/v1/list
v1.Get("/user", handler) // /api/v1/user
v2 := api.Group("/v2", middleware) // /api/v2
v2.Get("/list", handler) // /api/v2/list
v2.Get("/user", handler) // /api/v2/user
log.Fatal(app.Listen(":3000"))
}
이에 대한 자세한 내용은 Grouping 가이드를 참조하세요.