The iris framework has two modes for route binding, one is functional and the other is MVC. The functional mode binds a handling function to a specified URL path, while the MVC mode binds a controller to a URL path. The framework automatically generates corresponding URL paths based on the naming rules of the controller methods, and automatically binds the corresponding controller functions.

Functional Route Binding

The simplest routing model in the iris framework, where you can bind a function to any URL.

func main() {
    // Create an iris application with default middleware:
    // By default, it uses the "debug" log level.
    // It supports localization located under the "./locales" directory.
    // HTML templates are located under the "./views" or "./templates" directories.
    // Access logs are saved in "./access.log",
    // and recovery (without crashing) and request ID middleware are already attached.
    app := iris.Default()

	// Simply bind route functions based on the HTTP request method and path, similar to the routing mechanism in Gin, echo, and other frameworks.
    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)
    
	// Listen on port
    app.Listen(":8080")
}

Parameters in the Path

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

    // This handler will match /user/john but not /user/ or /user
    app.Get("/user/{name}", func(ctx iris.Context) {
        name := ctx.Params().Get("name")
        ctx.Writef("Hello %s", name)
    })
    
    // However, this handler will match /user/john/ and /user/john/send
    // If no other route matches /user/john, it will redirect to /user/john/
    app.Get("/user/{name}/{action:path}", func(ctx iris.Context) {
        name := ctx.Params().Get("name")
        action := ctx.Params().Get("action")
        message := name + " is " + action
        ctx.WriteString(message)
    })
    
    // For every matched request, Context will keep the route definition
    app.Post("/user/{name:string}/{action:path}", func(ctx iris.Context) {
        ctx.GetCurrentRoute().Tmpl().Src == "/user/{name:string}/{action:path}" // true
    })
    
    app.Listen(":8080")
}

Available built-in parameter types:

Parameter Type Go Type Validation Condition Retrieval Method
:string string Any character (single path segment) Params().Get
:uuid string uuidv4 or v1 format (single path segment) Params().Get
:int int -9223372036854775808 to 9223372036854775807 (x64) or -2147483648 to 2147483647 (x32), depending on the host architecture Params().GetInt
:int8 int8 -128 to 127 Params().GetInt8
:int16 int16 -32768 to 32767 Params().GetInt16
:int32 int32 -2147483648 to 2147483647 Params().GetInt32
:int64 int64 -9223372036854775808 to 9223372036854775807 Params().GetInt64
:uint uint 0 to 18446744073709551615 (x64) or 0 to 4294967295 (x32), depending on the host architecture Params().GetUint
:uint8 uint8 0 to 255 Params().GetUint8
:uint16 uint16 0 to 65535 Params().GetUint16
:uint32 uint32 0 to 4294967295 Params().GetUint32
:uint64 uint64 0 to 18446744073709551615 Params().GetUint64
:bool bool "1" or "t" or "T" or "TRUE" or "true" or "True" or "0" or "f" or "F" or "FALSE" or "false" or "False" Params().GetBool
:alphabetical string Lowercase or uppercase letters Params().Get
:file string Lowercase or uppercase letters, numbers, underscore (_), hyphen (-), dot (.), cannot contain spaces or other invalid special characters for file names Params().Get
:path string Any character, can be separated by slash (path segment), but should be the last part of the route path Params().Get
:mail string Email address, domain not validated Params().Get
:email string Email address, domain validated Params().Get
:date string Format yyyy/mm/dd, for example /blog/{param:date} matches /blog/2022/04/21 Params().GetTime and Params().SimpleDate
:weekday uint (0-6) or string String format as the long name of time.Weekday ("sunday" to "monday" or "Sunday" to "Monday"), for example /schedule/{param:weekday} matches /schedule/monday Params().GetWeekday

Group Routing

Sometimes, API version management is needed, or a unified prefix is set for the routing of a large module. This is where the ability of group routing comes in.

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

    // Simple group: v1
    v1 := app.Party("/v1")
    {
        v1.Post("/login", loginEndpoint)
        v1.Post("/submit", submitEndpoint)
        v1.Post("/read", readEndpoint)
    }
    
    // Simple group: v2
    v2 := app.Party("/v2")
    {
        v2.Post("/login", loginEndpoint)
        v2.Post("/submit", submitEndpoint)
        v2.Post("/read", readEndpoint)
    }
    
    app.Listen(":8080")
}

MVC Routing

The Go Iris framework supports the MVC architecture, mapping routes to specific controller functions through certain rules.

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

// Create an iris application
func newApp() *iris.Application {
	app := iris.New()
	// Set two middleware
	// recover is used to intercept panic errors to avoid abnormal program termination
	// logger is used to log requests
	app.Use(recover.New())
	app.Use(logger.New())

	// Register the controller to the "/" root route here.
	mvc.New(app).Handle(new(ExampleController))
	
	// It can also be registered to a specific path with the help of route grouping
	// Example: Register the controller under the /books path
	// mvc.New(app.Party("/books")).Handle(new(ExampleController))
}

func main() {
	// Create the application
	app := newApp()

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

// Define ExampleController to handle requests for "/", "/ping", and "/hello".
type ExampleController struct{}

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

// GetPing serves
// Method:   GET
// Request URL: http://localhost:8080/ping
func (c *ExampleController) GetPing() string {
	return "pong"
}

// GetHello serves
// Method:   GET
// Request URL: http://localhost:8080/hello
func (c *ExampleController) GetHello() interface{} {
	return map[string]string{"message": "Hello Iris!"}
}

// GetHelloWorld serves
// Method:   GET
// Request URL: http://localhost:8080/hello/world
func (c *ExampleController) GetHelloWorld() interface{} {
	return map[string]string{"message": "Hello Iris! DefaultPath"}
}

Relationship between MVC routing and the naming rule of controller functions.

Route Address: Route Group + HTTP method name + Function name (lowercase)

For example:

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

Because no route grouping is set, this function can handle GET requests for the route http://localhost:8080/ping.