본문 바로가기
개발/Fiber

[Fiber] Fiber Routing과 Grouping

by devhooney 2022. 11. 7.
728x90

Fiber Routing과 Grouping

Fiber의 Routing은 URI가 클라이언트의 요청에 응답하는 방식을 나타낸다.

 

- Path

Path는 문자열, 문자열 패턴으로 이루어져있다.

app.Get("/", func(c *fiber.Ctx) error {
      return c.SendString("root")
})

app.Get("/about", func(c *fiber.Ctx) error {
    return c.SendString("about")
})

app.Get("/random.txt", func(c *fiber.Ctx) error {
    return c.SendString("random.txt")
})

 

 

- Parameter

Parameter는 받을 수 있고, 선택적으로 받을 수 있다.

// 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
})
// +는 Parameter가 꼭 있어야 한다.
app.Get("/user/+", func(c *fiber.Ctx) error {
    return c.SendString(c.Params("+"))
})

// Optional parameter
app.Get("/user/:name?", func(c *fiber.Ctx) error {
    return c.SendString(c.Params("name"))
})

// Wildcard - optional
app.Get("/user/*", func(c *fiber.Ctx) error {
    return c.SendString(c.Params("*"))
})

 

 

- Paramter의 제약조건

지키지 않을 경우 404를 리턴한다.

Constraint Example Example matches
int
:id<int>
123456789, -123456789
bool
:active<bool>
true,false
guid
:id
CD2C1638-1638-72D5-1638-DEADBEEF1638
float
:weight<float>
1.234, -1,001.01e8
minLen(value)
:username<minLen(4)>
Test (must be at least 4 characters)
maxLen(value)
:filename<maxLen(8)>
MyFile (must be no more than 8 characters
len(length)
:filename<len(12)>
somefile.txt (exactly 12 characters)
min(value)
:age<min(18)>
19 (Integer value must be at least 18)
max(value)
:age<max(120)>
91 (Integer value must be no more than 120)
range(min,max)
:age<range(18,120)>
91 (Integer value must be at least 18 but no more than 120)
alpha
:name<alpha>
Rick (String must consist of one or more alphabetical characters, a-z and case-insensitive)
datetime
:dob<datetime(2006\\-01\\-02)>
2005-11-01
regex(expression)
:date<regex(\d{4}-\d{2}-\d{2})}>
2022-08-27 (Must match regular expression)

 

 

 

- Middleware

요청을 받기 전이나, 응답하기 전에 수정이나 변화를 할 때 사용한다.

스프링 필터나 인터셉터와 비슷한 역할을 한다고 생각하면 좋다.

app.Use(func(c *fiber.Ctx) error {
  // Set some security headers:
  c.Set("X-XSS-Protection", "1; mode=block")
  c.Set("X-Content-Type-Options", "nosniff")
  c.Set("X-Download-Options", "noopen")
  c.Set("Strict-Transport-Security", "max-age=5184000")
  c.Set("X-Frame-Options", "SAMEORIGIN")
  c.Set("X-DNS-Prefetch-Control", "off")

  // Go to next middleware:
  return c.Next()
})

app.Get("/", func(c *fiber.Ctx) error {
  return c.SendString("Hello, World!")
})

 

 

- Grouping

URI가 겹치는 라우터끼리 그룹을 지을 수 있다.

func main() {
    app := fiber.New()

    handler := func(c *fiber.Ctx) error {
        return c.SendStatus(fiber.StatusOK)
    }
    api := app.Group("/api") // /api

    v1 := api.Group("/v1", func(c *fiber.Ctx) error { // middleware for /api/v1
        c.Set("Version", "v1")
        return c.Next()
    })
    v1.Get("/list", handler) // /api/v1/list
    v1.Get("/user", handler) // /api/v1/user

    log.Fatal(app.Listen(":3000"))
}

 

 

- 참조

https://docs.gofiber.io/guide/routing#paths

 

Routing - Fiber

You should use \\ before routing-specific characters when to use datetime constraint (*, +, ?, :, /, <, >, ;, (, )), to avoid wrong parsing.

docs.gofiber.io

 

728x90

'개발 > Fiber' 카테고리의 다른 글

[Fiber] Fiber Template 사용하기  (1) 2022.11.08
[Fiber] Fiber 설정 및 에러  (0) 2022.11.05
[Fiber] Fiber 기본  (0) 2022.11.04
[Fiber] Go로 DB Connect하기(MariaDB)  (0) 2022.08.13
[Fiber] Go로 Backend 시작하기  (2) 2022.08.10