이 장에서는 iris 프레임워크에서 GET, POST 및 기타 요청 매개변수를 가져오는 방법을 소개하며, 쿠키를 읽고 쓰는 방법을 포함합니다.

경로의 매개변수

func main() {
    app := iris.Default()

    // 이 핸들러는 /user/john에는 일치하지만 /user/ 또는 /user에는 일치하지 않습니다.
    app.Get("/user/{name}", func(ctx iris.Context) {
        name := ctx.Params().Get("name")
        ctx.Writef("안녕 %s", name)
    })
    
    // 그러나 이 핸들러는 /user/john/ 및 /user/john/send에는 일치합니다.
    // 다른 라우터가 /user/john에 일치하지 않으면 /user/john/로 리디렉션됩니다.
    app.Get("/user/{name}/{action:path}", func(ctx iris.Context) {
        name := ctx.Params().Get("name")
        action := ctx.Params().Get("action")
        message := name + "은 " + action + "합니다"
        ctx.WriteString(message)
    })
    
    // 각 일치하는 요청에 대해 컨텍스트는 라우터의 정의를 유지합니다.
    app.Post("/user/{name:string}/{action:path}", func(ctx iris.Context) {
        ctx.GetCurrentRoute().Tmpl().Src == "/user/{name:string}/{action:path}" // true
    })
    
    app.Listen(":8080")
}

내장 가능한 매개변수 유형:

매개변수 유형 Go 타입 유효성 검사 접근 도우미 함수
:string string 모든 콘텐츠 (단일 경로 세그먼트) Params().Get
:uuid string uuidv4 또는 v1 (단일 경로 세그먼트) Params().Get
:int int -9223372036854775808에서 9223372036854775807 (x64) 또는 -2147483648에서 2147483647 (x32), 호스트 아키텍처에 따라 다름 Params().GetInt
:int8 int8 -128에서 127 Params().GetInt8
:int16 int16 -32768에서 32767 Params().GetInt16
:int32 int32 -2147483648에서 2147483647 Params().GetInt32
:int64 int64 -9223372036854775808에서 9223372036854775807 Params().GetInt64
:uint uint 0에서 18446744073709551615 (x64) 또는 0에서 4294967295 (x32), 호스트 아키텍처에 따라 다름 Params().GetUint
:uint8 uint8 0에서 255 Params().GetUint8
:uint16 uint16 0에서 65535 Params().GetUint16
:uint32 uint32 0에서 4294967295 Params().GetUint32
:uint64 uint64 0에서 18446744073709551615 Params().GetUint64
:bool bool "1" 또는 "t" 또는 "T" 또는 "TRUE" 또는 "true" 또는 "True" 또는 "0" 또는 "f" 또는 "F" 또는 "FALSE" 또는 "false" 또는 "False" Params().GetBool
:alphabetical string 소문자 또는 대문자 알파벳 Params().Get
:file string 소문자 또는 대문자 알파벳, 숫자, 밑줄(_), 하이픈(-), 점(.), 공백이나 다른 유효하지 않은 파일 이름 특수 문자를 포함할 수 없음 Params().Get
:path string 모든 콘텐츠, 슬래시로 분리될 수 있음 (경로 세그먼트), 하지만 라우트 경로의 마지막 부분이어야 함 Params().Get
:mail string 이메일 주소, 도메인 확인되지 않음 Params().Get
:email string 이메일 주소, 도메인 확인됨 Params().Get
:date string 형식 yyyy/mm/dd, 예를 들면 /blog/{param:date}는 /blog/2022/04/21에 일치함 Params().GetTimeParams().SimpleDate
:weekday uint (0-6) 또는 string 문자열은 time.Weekday 상수 ("sunday"에서 "monday" 또는 "Sunday"에서 "Monday") 형식이어야 함, 예를 들면 /schedule/{param:weekday}는 /schedule/monday에 일치함 Params().GetWeekday

Getting Query Parameters

func main() {
    app := iris.Default()

    // 기존의 저수준 요청 객체를 사용하여 쿼리 문자열 매개변수를 구문 분석합니다.
    // 요청 URL 일치: /welcome?firstname=Jane&lastname=Doe
    app.Get("/welcome", func(ctx iris.Context) {
        firstname := ctx.URLParamDefault("firstname", "Guest")
        lastname := ctx.URLParam("lastname") // ctx.Request().URL.Query().Get("lastname")의 단축키

        ctx.Writef("안녕하세요 %s %s", firstname, lastname)
    })
    app.Listen(":8080")
}

Getting Form Parameters

func main() {
    app := iris.Default()

    app.Post("/form_post", func(ctx iris.Context) {
        message := ctx.PostValue("message")
        nick := ctx.PostValueDefault("nick", "익명")

        ctx.JSON(iris.Map{
            "상태":  "게시됨",
            "메시지": message,
            "닉네임":    nick,
        })
    })
    app.Listen(":8080")
}

쿼리 및 폼 매개변수의 결합된 예시

POST /post?id=1234&page=1 HTTP/1.1
Content-Type: application/x-www-form-urlencoded

name=kataras&message=this_is_great
func main() {
    app := iris.Default()

    app.Post("/post", func(ctx iris.Context) {
        id, err := ctx.URLParamInt("id", 0)
        if err != nil {
            ctx.StopWithError(iris.StatusBadRequest, err)
            return
        }

        page := ctx.URLParamIntDefault("page", 0)
        name := ctx.PostValue("name")
        message := ctx.PostValue("message")

        ctx.Writef("id: %d; page: %d; name: %s; message: %s", id, page, name, message)
    })
    app.Listen(":8080")
}
id: 1234; page: 1; name: kataras; message: this_is_great

POST 요청에서 쿼리 매개변수 검색

POST /post?id=a&id=b&id=c&name=john&name=doe&name=kataras
Content-Type: application/x-www-form-urlencoded
func main() {
    app := iris.Default()

    app.Post("/post", func(ctx iris.Context) {

        ids := ctx.URLParamSlice("id")
        names, err := ctx.PostValues("name")
        if err != nil {
            ctx.StopWithError(iris.StatusBadRequest, err)
            return
        }

        ctx.Writef("ids: %v; names: %v", ids, names)
    })
    app.Listen(":8080")
}
ids: [a b c], names: [john doe kataras]

쿠키 읽기/쓰기

import "github.com/kataras/iris/v12"

func main() {
    app := iris.Default()

    app.Get("/cookie", func(ctx iris.Context) {
        // 쿠키 읽기
        value := ctx.GetCookie("my_cookie")

        if value == "" {
            value = "설정되지 않음"
            // 쿠키 생성
            ctx.SetCookieKV("my_cookie", value)
            // 또는: ctx.SetCookie(&http.Cookie{...})
            // 쿠키 생성
            ctx.SetCookie("", "test", 3600, "/", "localhost", false, true)
        }

        ctx.Writef("쿠키 값: %s \n", value)
    })

    app.Listen(":8080")
}