잠귀 프레임워크는 두 가지 라우트 바인딩 모드를 가지고 있습니다. 하나는 기능적이고 다른 하나는 MVC입니다. 기능적 모드는 지정된 URL 경로에 처리 함수를 바인딩하며, MVC 모드는 URL 경로에 컨트롤러를 바인딩합니다. 프레임워크는 컨트롤러 메서드의 네이밍 규칙에 따라 해당하는 URL 경로를 자동으로 생성하고 해당하는 컨트롤러 함수를 자동으로 바인딩합니다.

기능적 라우트 바인딩

아이리스 프레임워크의 가장 간단한 라우팅 모델로, 어떠한 URL에도 함수를 바인딩할 수 있습니다.

func main() {
    // 기본 미들웨어를 사용하여 아이리스 애플리케이션을 생성:
    // 기본적으로 "debug" 로그 레벨을 사용합니다.
    // "./locales" 디렉토리에 위치한 로컬라이제이션을 지원합니다.
    // HTML 템플릿은 "./views" 또는 "./templates" 디렉토리에 위치합니다.
    // 액세스 로그는 "./access.log"에 저장되며,
    // 충돌 없는 복구와 요청 ID 미들웨어가 이미 첨부되어 있습니다.
    app := iris.Default()

	// Gin, echo 및 기타 프레임워크의 라우팅 메커니즘과 유사하게 HTTP 요청 메서드와 경로를 기반으로 한 라우트 함수를 간단하게 바인딩합니다.
    app.Get("/someGet", getting)
    app.Post("/somePost", posting)
    app.Put("/somePut", putting)
    app.Delete("/someDelete", deleting)
    app.Patch("/somePatch", patching)
    app.Header("/someHead", head)
    app.Options("/someOptions", options)
    
	// 포트에서 대기
    app.Listen(":8080")
}
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)
    })
    
    // 매치된 모든 요청에 대해 Context는 라우트 정의를 유지합니다.
    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 시간.요일의 긴 이름 형식으로 문자열 ("sunday"에서 "monday" 또는 "Sunday"에서 "Monday") 등, 예를 들어 /schedule/{param:weekday}는 /schedule/monday와 일치합니다 Params().GetWeekday

그룹 라우팅

가끔은 API 버전 관리가 필요하거나 대규모 모듈의 라우팅에 통합된 접두사가 설정되어야 할 수 있습니다. 이때 그룹 라우팅 기능이 필요합니다.

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

    // 간단한 그룹: v1
    v1 := app.Party("/v1")
    {
        v1.Post("/login", loginEndpoint)
        v1.Post("/submit", submitEndpoint)
        v1.Post("/read", readEndpoint)
    }
    
    // 간단한 그룹: v2
    v2 := app.Party("/v2")
    {
        v2.Post("/login", loginEndpoint)
        v2.Post("/submit", submitEndpoint)
        v2.Post("/read", readEndpoint)
    }
    
    app.Listen(":8080")
}

MVC 라우팅

Go Iris 프레임워크는 MVC 아키텍처를 지원하며, 특정 규칙을 통해 경로를 특정 컨트롤러 함수에 매핑합니다.

package main

import (
	"strings"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/middleware/logger"
	"github.com/kataras/iris/v12/middleware/recover"
	"github.com/kataras/iris/v12/mvc"
)

// 새 iris 어플리케이션 생성
func newApp() *iris.Application {
	app := iris.New()
	// 두 가지 미들웨어 설정
	// recover는 비정상적인 프로그램 종료를 피하기 위해 패닉 에러를 가로채는 데 사용됨
	// logger는 요청을 로깅하는 데 사용됨
	app.Use(recover.New())
	app.Use(logger.New())

	// 컨트롤러를 "/" 루트 경로에 등록
	mvc.New(app).Handle(new(ExampleController))
	
	// 경로 그룹화를 통해 특정 경로에 등록할 수도 있음
	// 예: 컨트롤러를 /books 경로에 등록
	// mvc.New(app.Party("/books")).Handle(new(ExampleController))
}

func main() {
	// 어플리케이션 생성
	app := newApp()

	// http://localhost:8080
	// http://localhost:8080/ping
	// http://localhost:8080/hello
	// http://localhost:8080/custom_path
	app.Listen(":8080")
}

// "/" , "/ping", "/hello"에 대한 요청을 처리할 ExampleController 정의
type ExampleController struct{}

// GET 요청 처리
// 요청 URL: http://localhost:8080
func (c *ExampleController) Get() mvc.Result {
	return mvc.Response{
		ContentType: "text/html",
		Text:        "<h1>Welcome</h1>",
	}
}

// GetPing 처리
// 메소드:   GET
// 요청 URL: http://localhost:8080/ping
func (c *ExampleController) GetPing() string {
	return "pong"
}

// GetHello 처리
// 메소드:   GET
// 요청 URL: http://localhost:8080/hello
func (c *ExampleController) GetHello() interface{} {
	return map[string]string{"message": "Hello Iris!"}
}

// GetHelloWorld 처리
// 메소드:   GET
// 요청 URL: http://localhost:8080/hello/world
func (c *ExampleController) GetHelloWorld() interface{} {
	return map[string]string{"message": "Hello Iris! DefaultPath"}
}

MVC 라우팅과 컨트롤러 함수의 네이밍 규칙 간의 관계

경로 주소: 라우트 그룹 + HTTP 메소드 이름 + 함수 이름 (소문자)

예를 들어:

func (c *ExampleController) GetPing() string {
	return "pong"
}

라우트 그룹화가 설정되어 있지 않으므로, 해당 함수가 http://localhost:8080/ping 경로의 GET 요청을 처리할 수 있습니다.