### Getting Started with Iris Examples Source: https://iris-go.com/docs/resources/examples This snippet shows how to clone the Iris repository, navigate to the examples directory, select a specific example (like 'hello-world'), and run it using the Go compiler. ```bash git clone https://github.com/kataras/iris.git cd iris/_examples ``` ```bash cd basic/hello-world ``` ```bash go run main.go ``` -------------------------------- ### Install Iris Go Framework Source: https://iris-go.com/docs/getting-started/installation This snippet shows the commands to create a new Go project, initialize Go modules, and install the latest version of the Iris framework. ```bash mkdir myapp cd myapp go mod init myapp go get github.com/kataras/iris/v12@latest ``` -------------------------------- ### Initialize Go Module and Get Iris Source: https://iris-go.com/docs/mvc/mvc-quickstart Commands to initialize a new Go module for the project and fetch the latest Iris framework. This sets up the project for dependency management. ```bash $ go mod init app $ go get -u github.com/kataras/iris/v12@main # or @latest for the latest stable release. ``` -------------------------------- ### Create Iris Go Application with MVC Source: https://iris-go.com/docs/getting-started/quick-start This Go code snippet demonstrates creating an Iris web application using the Model-View-Controller (MVC) pattern. It sets up a party for '/books' and handles requests using a BookController, which defines GET and POST methods to align with HTTP verbs for book listing and creation. ```go import "github.com/kataras/iris/v12/mvc" func main() { app := iris.New() booksAPI := app.Party("/books") m := mvc.New(booksAPI) m.Handle(new(BookController)) app.Listen(":8080") } type BookController struct { /* dependencies */ } // GET: http://localhost:8080/books func (c *BookController) Get() []Book { return []Book{ {"Mastering Concurrency in Go"}, {"Go Design Patterns"}, {"Black Hat Go"}, } } // POST: http://localhost:8080/books func (c *BookController) Post(b Book) int { println("Received Book: " + b.Title) return iris.StatusCreated } ``` -------------------------------- ### Iris Go MVC Application Setup Source: https://iris-go.com/docs/mvc/mvc-quickstart This Go code sets up a new Iris web application. It configures a health check endpoint ('/ping') and sets up an MVC application party for '/greet'. Dependencies such as environment configuration, database connections, and greeting services are registered before handling the GreetController. ```go package main import ( "app/controller" "app/database" "app/environment" "app/service" "github.com/kataras/iris/v12" "github.com/kataras/iris/v12/mvc" ) func main() { app := iris.New() app.Get("/ping", pong).Describe("healthcheck") mvc.Configure(app.Party("/greet"), setup) // http://localhost:8080/greet?name=kataras app.Listen(":8080", iris.WithLogLevel("debug")) } func pong(ctx iris.Context) { ctx.WriteString("pong") } func setup(app *mvc.Application) { // Register Dependencies. app.Register( environment.DEV, // DEV, PROD database.NewDB, // sqlite, mysql service.NewGreetService, // greeterWithLogging, greeter ) // Register Controllers. app.Handle(new(controller.GreetController)) } ``` -------------------------------- ### Go Greet Controller Source: https://iris-go.com/docs/mvc/mvc-quickstart Implements the GreetController which handles GET requests to the '/greet' path. It depends on the GreetService to process the request and return a response. ```go package controller import ( "app/model" "app/service" ) type GreetController struct { Service service.GreetService // Ctx iris.Context } func (c *GreetController) Get(req model.Request) (model.Response, error) { message, err := c.Service.Say(req.Name) if err != nil { return model.Response{}, err } return model.Response{Message: message}, nil } ``` -------------------------------- ### Create Basic Iris Go Application Source: https://iris-go.com/docs/getting-started/quick-start This Go code snippet demonstrates how to create a basic Iris web application. It sets up a party for '/books' with compression middleware and defines GET and POST handlers for listing and creating books, respectively. It also includes a Book struct for JSON handling and the main application listen function. ```go package main import "github.com/kataras/iris/v12" func main() { app := iris.New() booksAPI := app.Party("/books") { booksAPI.Use(iris.Compression) // GET: http://localhost:8080/books booksAPI.Get("/", list) // POST: http://localhost:8080/books booksAPI.Post("/", create) } app.Listen(":8080") } // Book example. type Book struct { Title string `json:"title"` } func list(ctx iris.Context) { books := []Book{ {"Mastering Concurrency in Go"}, {"Go Design Patterns"}, {"Black Hat Go"}, } ctx.JSON(books) // TIP: negotiate the response between server's prioritizes // and client's requirements, instead of ctx.JSON: // ctx.Negotiation().JSON().MsgPack().Protobuf() // ctx.Negotiate(books) } func create(ctx iris.Context) { var b Book err := ctx.ReadJSON(&b) // TIP: use ctx.ReadBody(&b) to bind // any type of incoming data instead. if err != nil { ctx.StopWithProblem(iris.StatusBadRequest, iris.NewProblem(). Title("Book creation failure").DetailErr(err)) // TIP: use ctx.StopWithError(code, err) when only // plain text responses are expected on errors. return } println("Received Book: " + b.Title) ctx.StatusCode(iris.StatusCreated) } ``` -------------------------------- ### Run Iris Go application Source: https://iris-go.com/docs/mvc/mvc-quickstart This snippet shows how to run the Iris Go application using the `go run` command. It assumes that Go is installed and configured correctly on the system. ```bash go run main.go ``` -------------------------------- ### Basic Iris MVC Application Setup Source: https://iris-go.com/docs/mvc/mvc Demonstrates the fundamental setup of an Iris MVC application. It includes creating a new Iris app, configuring an MVC party, handling a controller, and starting the server. ```Go import ( "github.com/kataras/iris/v12" "github.com/kataras/iris/v12/mvc" ) func main() { app := iris.New() mvc.Configure(app.Party("/root"), myMVC) app.Listen(":8080") } func myMVC(app *mvc.Application) { // app.Register(...) // app.Router.Use/UseGlobal/Done(...) app.Handle(new(MyController)) } type MyController struct {} func (m *MyController) BeforeActivation(b mvc.BeforeActivation) { // b.Dependencies().Add/Remove // b.Router().Use/UseGlobal/Done // and any standard Router API call you already know // 1-> Method // 2-> Path // 3-> The controller's function name to be parsed as handler // 4-> Any handlers that should run before the MyCustomHandler b.Handle("GET", "/something/{id:int64}", "MyCustomHandler", anyMiddleware...) } // GET: http://localhost:8080/root func (m *MyController) Get() string { return "Hey" } // GET: http://localhost:8080/root/something/{id:int64} func (m *MyController) MyCustomHandler(id int64) string { return "MyCustomHandler says Hey" } ``` -------------------------------- ### Import Iris in Go Code Source: https://iris-go.com/docs/getting-started/installation Demonstrates how to import the Iris framework into your Go project files. ```go import "github.com/kataras/iris/v12" ``` -------------------------------- ### Go Greet Service Implementation Source: https://iris-go.com/docs/mvc/mvc-quickstart Defines the GreetService interface and provides two implementations: a basic greeter and a greeter with logging. The service depends on environment configuration and a database connection. ```go package service import ( "fmt" "app/database" "app/environment" ) // GreetService example service. type GreetService interface { Say(input string) (string, error) } // NewGreetService returns a service backed with a "db" based on "env". func NewGreetService(env environment.Env, db database.DB) GreetService { service := &greeter{db: db, prefix: "Hello"} switch env { case environment.PROD: return service case environment.DEV: return &greeterWithLogging{service} default: panic("unknown environment") } } type greeter struct { prefix string db database.DB } func (s *greeter) Say(input string) (string, error) { if err := s.db.Exec("simulate a query..."); err != nil { return "", err } result := s.prefix + " " + input return result, nil } type greeterWithLogging struct { *greeter } func (s *greeterWithLogging) Say(input string) (string, error) { result, err := s.greeter.Say(input) fmt.Printf("result: %s\nerror: %v\n", result, err) return result, err } ``` -------------------------------- ### Run Iris Go Application Source: https://iris-go.com/docs/getting-started/quick-start This shell command shows how to run the Iris Go web application from the command line. It assumes the main application file is named 'main.go'. ```sh $ go run main.go > Now listening on: http://localhost:8080 > Application started. Press CTRL+C to shut down. ``` -------------------------------- ### Run Iris Go application with Docker Source: https://iris-go.com/docs/mvc/mvc-quickstart This snippet shows how to run the Iris Go application using Docker. It assumes that Docker and Docker Compose are installed and configured correctly. The Dockerfile and docker-compose.yml files should be located in the `app` folder. ```bash $ docker-compose up ``` -------------------------------- ### Iris Starter Kits and Examples Source: https://iris-go.com/docs/resources/starter-kits This section lists various community-contributed starter kits and example projects for the Iris web framework. These projects showcase different combinations of technologies and use cases, such as integrating with databases (GORM, xorm), authentication (JWT, Casbin), and front-end frameworks (Vue, React). ```Go Project | Description | Stars | Author ---|---|---|--- peterq/pan-light | Baidu network disk unlimited speed client, golang + qt5, cross-platform graphical interface | 10460 | @peterq eltaline/wzd | wZD is a powerful storage and database server, designed for big data storage systems with small and large files for mixed use and dramatically reduces count of small files for extend abilities any normal or clustered POSIX compatible file systems | 68 | @eltaline eltaline/ctrl | cTRL is a server for remote execution of pending tasks and commands in real time, supporting a queue with continuous thread limiting and throttling | 2 | @eltaline mlogclub/bbs-go | Golang-based community system | 527 | @mlogclub snowlyg/IrisApiProject | Iris + gorm + JWT + sqlite3 | 359 | @snowlyg mohuishou/scuplus-go | WeChat applet Backend API | 62 | @mohuishou menghx/levante | **BLOG** powered by Iris! | 7 | @menghx zuoyanart/pizzaCmsApi | RESTful power by Iris | 37 | @zuoyanart wx85278161/go-iris-vue | Iris + Vue + Casbin + JWT | 61 | @wx85278161 yz124/superstar | Iris + xorm to implement the star library | 105 | @yz124 pusher.com | A realtime API monitor written with go | 5 | @neoighodaro jebzmos4/Iris-golang | A basic CRUD API in golang with Iris | 8 | @jebzmos4 gauraavtiwari/go_iris_app | Basic web app built in Iris | 21 | @gauravtiwari iris-contrib/Iris-Mini-Social-Network | A mini social-network created with the awesome Iris๐๐ | 49 | @iris-contrib iris-contrib/iris-starter-kit | Iris isomorphic react/hot reloadable/redux/css-modules | 38 | @iris-contrib TimothyYe/iris-demo | Iris demo project | 2 | @TimothyYe ionutvilie/react-ts | Demo project with react using typescript and Iris | 10 | @ionutvilie iris-contrib/parrot | Self-hosted Localization Management Platform built with Iris and Angular | 9 | @iris-contrib iris-contrib/cloud-native-go | Iris + Docker and Kubernetes | 28 | @iris-contrib nanobox.io | Quickstart for Iris with Nanobox | 9 | @nanobox-io hasura.io | A Hasura starter project with a ready to deploy Golang hello-world web app with Iris | 9 | @k8s-platform-hub ``` -------------------------------- ### Clean Go Modules Cache Source: https://iris-go.com/docs/getting-started/installation Shows the command to clean the Go modules cache, a troubleshooting step for persistent installation or dependency issues. ```sh go clean --modcache ``` -------------------------------- ### Iris Go SetHost Example Source: https://iris-go.com/docs/redirect/multi-app-instances An example demonstrating the use of `SetHost` with the `Hosts` provider to normalize the host header for routing, ensuring consistent application behavior. ```go cases := Hosts{ {"^(www.)?mydomain.com$", rootApp}, } switcher := Switch(cases, SetHost("mydomain.com")) ``` -------------------------------- ### SQLite Database Implementation in Go Source: https://iris-go.com/docs/mvc/mvc-quickstart A concrete implementation of the `DB` interface for SQLite. Its `Exec` method is a no-op, returning nil, suitable for development environments. ```go package database type sqlite struct{} func (db *sqlite) Exec(q string) error { return nil } ``` -------------------------------- ### Install Protoc Go Plugin Source: https://iris-go.com/docs/mvc/mvc-grpc Installs the protoc Go plugin, which is necessary for generating Go code from .proto files. ```bash $ go get -u github.com/golang/protobuf/protoc-gen-go ``` -------------------------------- ### Iris Go Switch Example Usage Source: https://iris-go.com/docs/redirect/multi-app-instances An example demonstrating how to use the `Switch` function with the `Hosts` provider to route requests based on domain names to different Iris applications. ```go switcher := Switch(Hosts{ "mydomain.com": app, "test.mydomain.com": testSubdomainApp, "otherdomain.com": "appName", }) switcher.Listen(":80") ``` -------------------------------- ### Install go-bindata Source: https://iris-go.com/docs/file-server/http2push-embedded-compression Installs the go-bindata tool, which is used to embed static assets into Go executables. This is a prerequisite for the file serving example. ```sh go get -u github.com/go-bindata/go-bindata/... ``` -------------------------------- ### Install CORS Middleware Source: https://iris-go.com/docs/security/cors Installs the CORS middleware from the iris-contrib/middleware repository using go get. ```shell $ go get github.com/iris-contrib/middleware/jwt@master ``` -------------------------------- ### MySQL Database Implementation in Go Source: https://iris-go.com/docs/mvc/mvc-quickstart A concrete implementation of the `DB` interface for MySQL. It includes an `Exec` method that simulates execution and returns an error indicating it's not implemented. ```go package database import "fmt" type mysql struct{} func (db *mysql) Exec(q string) error { return fmt.Errorf("mysql: not implemented <%s>", q) } ``` -------------------------------- ### Set GOPROXY for Network Issues Source: https://iris-go.com/docs/getting-started/installation Provides the command to set the GOPROXY environment variable, which can resolve network errors during Go module downloads. ```sh go env -w GOPROXY=https://goproxy.io,direct ``` -------------------------------- ### Install Iris Go Framework Source: https://iris-go.com/docs/index This snippet shows the command to install the latest version of the Iris Go web framework using the Go package manager. ```bash go get github.com/kataras/iris/v12@latest ``` -------------------------------- ### Environment Configuration in Go Source: https://iris-go.com/docs/mvc/mvc-quickstart Defines an `Env` type and a `ReadEnv` function to manage application environments (development and production). It reads environment variables and validates them. ```go package environment import ( "os" "strings" ) const ( PROD Env = "production" DEV Env = "development" ) type Env string func (e Env) String() string { return string(e) } func ReadEnv(key string, def Env) Env { v := Getenv(key, def.String()) if v == "" { return def } env := Env(strings.ToLower(v)) switch env { case PROD, DEV: // allowed. default: panic("unexpected environment " + v) } return env } func Getenv(key string, def string) string { if v := os.Getenv(key); v != "" { return v } return def } ``` -------------------------------- ### Iris Go: HTTP 400 Bad Request Example Source: https://iris-go.com/docs/getting-started/quick-start This snippet shows a `curl` command making a POST request to an Iris Go application's `/books` endpoint with malformed JSON data. The response is an HTTP 400 Bad Request, indicating an issue with the request payload, specifically an invalid character in the JSON. ```bash $ curl -X POST --data "{\"title\" \"not valid one\"}" \ http://localhost:8080/books > HTTP/1.1 400 Bad Request { "status": 400, "title": "Book creation failure" "detail": "invalid character '"' after object key", } ``` -------------------------------- ### Iris Sitemap Example Source: https://iris-go.com/docs/i18n/sitemap A complete example demonstrating the Iris sitemap functionality. It includes setting up an Iris application, defining routes with sitemap-specific configurations (LastMod, ChangeFreq, Priority, ExcludeSitemap, SetStatusOffline), and listening on a port with sitemap enabled. ```go package main import ( time "time" "github.com/kataras/iris/v12" ) const startURL = "http://localhost:8080" func main() { app := newApp() // http://localhost:8080/sitemap.xml // Lists only online GET static routes. // // Reference: https://www.sitemaps.org/protocol.html app.Listen(":8080", iris.WithSitemap(startURL)) } func newApp() *iris.Application { app := iris.New() app.Logger().SetLevel("debug") lastModified, _ := time.Parse("2006-01-02T15:04:05-07:00", "2019-12-13T21:50:33+02:00") app.Get("/home", handler).SetLastMod(lastModified).SetChangeFreq("hourly").SetPriority(1) app.Get("/articles", handler).SetChangeFreq("daily") app.Get("/path1", handler) app.Get("/path2", handler) app.Post("/this-should-not-be-listed", handler) app.Get("/this/{myparam}/should/not/be/listed", handler) app.Get("/this-should-not-be-listed-offline", handler).SetStatusOffline() // These should be excluded as well app.Get("/about", handler).ExcludeSitemap() app.Get("/offline", handler).SetStatusOffline() return app } func handler(ctx iris.Context) { ctx.WriteString(ctx.Path()) } ``` -------------------------------- ### Database Interface and Factory in Go Source: https://iris-go.com/docs/mvc/mvc-quickstart Defines a `DB` interface for database operations and a `NewDB` function that acts as a factory to create specific database implementations (MySQL or SQLite) based on the environment. ```go package database import "app/environment" type DB interface { Exec(q string) error } func NewDB(env environment.Env) DB { switch env { case environment.PROD: return &mysql{} case environment.DEV: return &sqlite{} default: panic("unknown environment") } } ``` -------------------------------- ### Test List Books API with Curl Source: https://iris-go.com/docs/getting-started/quick-start This shell command uses curl to test the '/books' endpoint of the Iris application. It includes headers for accepting gzip encoding and requests the list of books, expecting a JSON response. ```sh $ curl --header 'Accept-Encoding:gzip' http://localhost:8080/books [ { "title": "Mastering Concurrency in Go" }, { "title": "Go Design Patterns" }, { "title": "Black Hat Go" } ] ``` -------------------------------- ### Go Request Model Source: https://iris-go.com/docs/mvc/mvc-quickstart Defines the structure for incoming HTTP requests, specifically expecting a 'Name' field to be provided as a URL query parameter. ```go package model type Request struct { Name string `url:"name"` } ``` -------------------------------- ### Full API Versioning Example in Go Source: https://iris-go.com/docs/routing/api-versioning A comprehensive example of setting up API versioning with Iris. It includes creating versioned route groups, handling errors per version, and registering handlers and views for different API versions (v1, v2, v3). ```go package main import ( "github.com/kataras/iris/v12" "github.com/kataras/iris/v12/versioning" ) func main() { app := iris.New() app.OnErrorCode(iris.StatusNotFound, func(ctx iris.Context) { ctx.WriteString(`Root not found handler. This will be applied everywhere except the /api/* requests.`) // Corrected: Added closing quote and semicolon }) api := app.Party("/api") // Optional, set version aliases (literal strings). // We use `UseRouter` instead of `Use` // to handle HTTP errors per version, but it's up to you. api.UseRouter(versioning.Aliases(versioning.AliasMap{ // If no version provided by the client, default it to the "1.0.0". versioning.Empty: "1.0.0", // If a "latest" version is provided by the client, // set the version to be compared to "3.0.0". "latest": "3.0.0", })) // |----------------| // | The fun begins | // |----------------| // Create a new Group, which is a compatible Party, // based on version constraints. v1 := versioning.NewGroup(api, ">=1.0.0 <2.0.0") // Optionally, set custom view engine and path // for templates based on the version. v1.RegisterView(iris.HTML("./v1", ".html")) // Optionally, set custom error handler(s) based on the version. // Keep in mind that if you do this, you will // have to register error handlers // for the rest of the parties as well. v1.OnErrorCode(iris.StatusNotFound, testError("v1")) // Register resources based on the version. v1.Get("/", testHandler("v1")) v1.Get("/render", testView) // Do the same for version 2 and version 3, // for the sake of the example. v2 := versioning.NewGroup(api, ">=2.0.0 <3.0.0") v2.RegisterView(iris.HTML("./v2", ".html")) v2.OnErrorCode(iris.StatusNotFound, testError("v2")) v2.Get("/", testHandler("v2")) v2.Get("/render", testView) v3 := versioning.NewGroup(api, ">=3.0.0 <4.0.0") v3.RegisterView(iris.HTML("./v3", ".html")) v3.OnErrorCode(iris.StatusNotFound, testError("v3")) v3.Get("/", testHandler("v3")) v3.Get("/render", testView) app.Listen(":8080") } func testHandler(v string) iris.Handler { return func(ctx iris.Context) { ctx.JSON(iris.Map{ "version": v, "message": "Hello, world!", }) } } func testError(v string) iris.Handler { return func(ctx iris.Context) { ctx.Writef("not found: %s", v) } } func testView(ctx iris.Context) { ctx.View("index.html") } ``` -------------------------------- ### Go Response Model Source: https://iris-go.com/docs/mvc/mvc-quickstart Defines the structure for HTTP responses, containing a 'Message' field that will be returned as JSON. ```go package model type Response struct { Message string `json:"msg"` } ``` -------------------------------- ### Install go-bindata Source: https://iris-go.com/docs/file-server/introduction This bash command installs the go-bindata tool, which is used to embed static files into Go programs. This allows applications to serve files without relying on external directories. ```bash $ go get -u github.com/go-bindata/go-bindata/v3/go-bindata ``` -------------------------------- ### Example Response for User Update Source: https://iris-go.com/docs/dependency-injection/dependency-injection Shows the expected JSON response from the Iris Go server after a successful user update operation. ```javascript { "id": 42, "message": "User updated successfully" } ``` -------------------------------- ### Test Create Book API with Curl Source: https://iris-go.com/docs/getting-started/quick-start This shell command demonstrates how to test the POST '/books' endpoint using curl. It sends a JSON payload with a book title and specifies content type and encoding, expecting a 201 Created status code. ```sh $ curl -i -X POST \ --header 'Content-Encoding:gzip' \ --header 'Content-Type:application/json' \ --data "{\"title\":\"Writing An Interpreter In Go\"}" \ http://localhost:8080/books > HTTP/1.1 201 Created ``` -------------------------------- ### Example Users YAML Configuration Source: https://iris-go.com/docs/security/basicauth Example YAML configuration file for storing user credentials. Passwords should be encrypted using bcrypt. ```yaml - username: kataras password: $2a$10$Irg8k8HWkDlvL0YDBKLCYee6j6zzIFTplJcvZYKA.B8/clHPZn2Ey # encrypted of kataras_pass role: admin - username: makis password: $2a$10$3GXzp3J5GhHThGisbpvpZuftbmzPivDMo94XPnkTnDe7254x7sJ3O # encrypted of makis_pass role: member ``` -------------------------------- ### Iris Go Basic Text Response Source: https://iris-go.com/docs/responses/text Demonstrates how to send a simple text response and a formatted text response using Iris. The first example sends 'Hello World' to the '/text' endpoint. The second example uses `Writef` to format a string with variables for the '/formatted' endpoint. ```go package main import "github.com/kataras/iris/v12" func main() { app := iris.New() app.Get("/text", func(ctx iris.Context) { ctx.Text("Hello World") }) app.Get("/formatted", func(ctx iris.Context) { name := "John" age := 25 ctx.Writef("Name: %s, Age: %d", name, age) }) app.Listen(":8080") } ``` -------------------------------- ### Iris Go: Redirect Example Source: https://iris-go.com/docs/redirect/context-redirect This Go code example demonstrates how to use the `Redirect` method in Iris to redirect a user from the `/home` route to the root `/` route with a permanent redirect status (301). It sets up a basic Iris application with two routes and their respective handlers. ```go package main import "github.com/kataras/iris/v12" func main() { app := iris.New() app.Get("/", index) app.Get("/home", home) app.Listen(":8080") } func index(ctx iris.Context) { ctx.Writef("Hello, %s!", "World") } func home(ctx iris.Context) { ctx.Redirect("/", iris.StatusPermanentRedirect) } ``` -------------------------------- ### Iris Go: Custom RoleMiddleware Example Source: https://iris-go.com/docs/dependency-injection/context-register-dependency An example of a custom Iris Go middleware, `RoleMiddleware`, that checks for a specific query parameter and sets a `Role` struct in the context values. It also demonstrates registering the `Role` as a dependency. ```go package main import "github.com/kataras/iris/v12" // Role struct value example. type Role struct { Name string } const roleContextKey = "myapp.role" // RoleMiddleware example of a custom middleware. func RoleMiddleware(ctx iris.Context) { // [do it yourself: extract the role from the request...] if ctx.URLParam("name") != "kataras" { ctx.StopWithStatus(iris.StatusUnauthorized) return } // role := Role{Name: "admin"} // Share the role value to the next handler(s). ctx.Values().Set(roleContextKey, role) ctx.RegisterDependency(role) ctx.Next() } ``` -------------------------------- ### Iris Go Join SwitchProviders Example Source: https://iris-go.com/docs/redirect/multi-app-instances Illustrates how to combine multiple routing providers, including custom `SwitchCase` filters and `Hosts` providers, using the `Join` function. ```go Switch(Join{ SwitchCase{ Filter: customFilter, App: myapp, }, Hosts{ {"^test.*$", myapp}, }, }) ``` -------------------------------- ### Example Response with Preflight Modifications Source: https://iris-go.com/docs/dependency-injection/dependency-injection Illustrates the JSON response after a handler with custom preflight logic is executed, showing updated fields like timestamp and HTTP status code. ```javascript { "message": "User has been marked for deletion", "code": 202, "timestamp": 1583313026 } ``` -------------------------------- ### Run Iris Server with TLS Source: https://iris-go.com/docs/mvc/mvc-grpc Starts the Iris application, listening for gRPC requests on port 443 using the generated TLS certificate and key. ```go app.Run(iris.TLS(":443", "server.crt", "server.key")) ``` -------------------------------- ### Generate go-bindata Source: https://iris-go.com/docs/file-server/prefixdir-function This snippet shows the commands to install the `go-bindata` tool and generate the `bindata.go` file from the `./data` directory. This file will contain the embedded assets. ```sh $ go get -u github.com/go-bindata/go-bindata/... $ go-bindata -fs ./data/... ``` -------------------------------- ### Install Iris CSRF Middleware Source: https://iris-go.com/docs/security/csrf Installs the Iris CSRF middleware using go get. This command fetches the latest version of the middleware from the specified repository. ```sh go get github.com/iris-contrib/middleware/csrf@master ``` -------------------------------- ### Iris Go: Main Application Setup with Middleware and Dependencies Source: https://iris-go.com/docs/dependency-injection/context-register-dependency Sets up an Iris Go application, applying the `RoleMiddleware` and configuring dependency injection for handlers. It demonstrates registering a dependency from context values for handlers that require it. ```go package main import "github.com/kataras/iris/v12" func main() { app := iris.New() app.Use(RoleMiddleware) app.Get("/", commonHandler) c := app.ConfigureContainer() c.RegisterDependency(func(ctx iris.Context) Role { role, ok := GetRole(ctx) if !ok { // This codeblock will never be executed here // but you can stop executing a handler which depends on // that dependency with // `ctx.StopExecution/ctx.StopWithXXX` methods // or by returning a second output argument of `error` type. ctx.StopExecution() return Role{} } return role }) c.Get("/dep", handlerWithDependencies) // http://localhost:8080?name=kataras // http://localhost:8080/dep?name=kataras app.Listen(":8080") } func commonHandler(ctx iris.Context) { role, _ := GetRole(ctx) ctx.WriteString(role.Name) } func handlerWithDependencies(role Role) string { return role.Name } ``` -------------------------------- ### Iris Go MVC Hello World App Source: https://iris-go.com/docs/mvc/mvc This Go code sets up a basic Iris web application using the MVC pattern. It includes middleware for recovery and logging, and defines an `ExampleController` to handle root, ping, and hello routes, along with a custom path. ```go package main import ( "github.com/kataras/iris/v12" "github.com/kataras/iris/v12/mvc" "github.com/kataras/iris/v12/middleware/logger" "github.com/kataras/iris/v12/middleware/recover" ) func main() { app := iris.New() // Optionally, add two built'n handlers // that can recover from any http-relative panics // and log the requests to the terminal. app.Use(recover.New()) app.Use(logger.New()) // Serve a controller based on the root Router, "/". mvc.New(app).Handle(new(ExampleController)) // http://localhost:8080 // http://localhost:8080/ping // http://localhost:8080/hello // http://localhost:8080/custom_path app.Listen(":8080") } // ExampleController serves the "/", "/ping" and "/hello". type ExampleController struct{} // Get serves // Method: GET // Resource: http://localhost:8080 func (c *ExampleController) Get() mvc.Result { return mvc.Response{ ContentType: "text/html", Text: "