Go Fiber Framework에서 다양한 요청 매개변수 처리

간단한 예제

Fiber 프레임워크의 모든 요청 매개변수는 context 객체 Ctx를 통해 얻습니다.

app.Get("/user/:name?", func(c *fiber.Ctx) error {
    // 라우트 함수의 Ctx 매개변수를 통해 매개변수를 얻고 적절한 메소드를 호출합니다
    // 여기서 Params를 사용하여 name 매개변수를 얻습니다
    return c.SendString(c.Params("name"))
})

라우트 매개변수 얻기

URL 경로에서 매개변수를 얻기

// 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"
  
  c.Params("*", "기본 값")  // 두 번째 매개변수로 기본 값을 설정할 수 있습니다
})

Int 형식의 라우트 매개변수 얻기

// GET http://example.com/user/123
app.Get("/user/:id", func(c *fiber.Ctx) error {
  id, err := c.ParamsInt("id") // int 123, 에러 없음

  // ...
})

GET 요청 쿼리 매개변수 얻기

// 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"

  // ...
})

모든 쿼리 매개변수 반환하기

// 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"]          // ""
    // ...
})

쿼리 매개변수를 구조체 객체에 바인딩하기

// 매개변수를 받기 위한 구조체 정의
// query 태그를 사용하여 바인딩할 매개변수 이름을 지정합니다
type Person struct {
    Name     string     `query:"name"`
    Pass     string     `query:"pass"`
    Products []string   `query:"products"`
}

app.Get("/", func(c *fiber.Ctx) error {
        // 매개변수를 받을 구조체 변수를 정의합니다
        p := new(Person)

        // QueryParser를 사용하여 쿼리 매개변수를 변수 p에 바인딩합니다
        if err := c.QueryParser(p); err != nil {
            return err
        }

        log.Println(p.Name)     // john
        log.Println(p.Pass)     // doe
        log.Println(p.Products) // [shoe, hat]

        // ...
})
// 테스트를 위해 다음 curl 명령을 실행하십시오
// curl "http://localhost:3000/?name=john&pass=doe&products=shoe,hat"

POST 요청 폼 매개변수 얻기

app.Post("/", func(c *fiber.Ctx) error {
    // 폼 필드 "name"에서 첫 번째 값을 가져옵니다:
    c.FormValue("name")
    // => "john", 존재하지 않으면 ""
    
    // ...
})

Body Parameters 처리

주로 POST/PUT 요청을 처리하며 JSON, XML 및 폼 매개변수를 지원합니다.

// 매개변수를 수신하는 구조체 정의 및 json, xml 및 form 태그를 통해 수신할 매개변수 필드 이름을 정의합니다.
// json, xml, form은 필요에 따라 선택할 수 있으며, 모두 포함할 필요는 없습니다.
type Person struct {
    Name string `json:"name" xml:"name" form:"name"`
    Pass string `json:"pass" xml:"pass" form:"pass"`
}

app.Post("/", func(c *fiber.Ctx) error {
    // 매개변수를 수신할 구조체 변수 정의
    p := new(Person)

    // BodyParser를 사용하여 body 매개변수를 변수 p에 바인딩합니다.
    if err := c.BodyParser(p); err != nil {
        return err
    }

    log.Println(p.Name) // john
    log.Println(p.Pass) // doe

    // ...
})

// 다양한 유형의 요청 예제; JSON 형식 매개변수 요청의 경우 Content-Type: application/json을 설정하는 것을 기억하세요.

// curl -X POST -H "Content-Type: application/json" --data "{\"name\":\"john\",\"pass\":\"doe\"}" localhost:3000

// curl -X POST -H "Content-Type: application/xml" --data "<login><name>john</name><pass>doe</pass></login>" localhost:3000

// curl -X POST -H "Content-Type: application/x-www-form-urlencoded" --data "name=john&pass=doe" localhost:3000

// curl -X POST -F name=john -F pass=doe http://localhost:3000

// curl -X POST "http://localhost:3000/?name=john&pass=doe"

원본 본문 데이터 검색 방법은 다음과 같습니다.

// curl -X POST http://localhost:8080 -d user=john

app.Post("/", func(c *fiber.Ctx) error {
  // BodyRaw를 사용하여 원시 본문 데이터 반환
  return c.Send(c.BodyRaw()) // []byte("user=john")
})

요청 헤더 검색

app.Get("/", func(c *fiber.Ctx) error {
  c.Get("Content-Type")       // "text/plain"
  c.Get("CoNtEnT-TypE")       // "text/plain"
  c.Get("something", "john")  // "john"
  // ...
})

클라이언트 IP 검색

app.Get("/", func(c *fiber.Ctx) error {
  c.IP() // "127.0.0.1"

  // ...
})

프록시나 로드 밸런서를 사용하여 서버에 배포된 경우 x-forwarded-for 헤더를 통해 클라이언트 IP를 검색하려면 다음과 같이 설정해야 합니다.

app := fiber.New(fiber.Config{
  ProxyHeader: fiber.HeaderXForwardedFor,
})

쿠키 읽기

app.Get("/", func(c *fiber.Ctx) error {
  // 키로 쿠키 가져오기:
  c.Cookies("name")         // "john"
  c.Cookies("empty", "doe") // "doe"
  // ...
})