### Install Quicktemplate Package and Compiler
Source: https://github.com/kataras/iris/blob/main/_examples/view/quicktemplate/README.md
Install the Quicktemplate package and its compiler using go get. These are necessary for using Quicktemplate in your Go projects.
```shell
go get -u github.com/valyala/quicktemplate
go get -u github.com/valyala/quicktemplate/qtc
```
--------------------------------
### Iris MVC Application Setup
Source: https://github.com/kataras/iris/blob/main/_examples/mvc/overview/README.md
This Go code demonstrates the basic setup of an Iris application using the MVC pattern. It configures routes, registers dependencies, and handles controllers for the '/greet' path. Ensure Iris and its MVC package are installed.
```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))
}
```
--------------------------------
### Install Iris using Go Get
Source: https://github.com/kataras/iris/wiki/Installation
Installs the Iris framework and its specific version using the 'go get' command. This is the recommended way to add Iris to your project.
```bash
$ go get github.com/kataras/iris/v12@v12.1.8
```
--------------------------------
### Party Configuration Example
Source: https://github.com/kataras/iris/blob/main/_proposals/xerrors_party.md
This example demonstrates how to configure a Party for the '/api' route, setting up handlers for Create, Update, Delete, List, and Get operations, along with request validation.
```APIDOC
## Party Configuration
This section details how to configure a `Party` instance to handle various API operations.
### Method
`app.PartyConfigure(path string, party *Party[CreateRequest, CreateResponse, ListFilter])`
### Parameters
- `path` (string): The base path for the party.
- `party` (*Party[CreateRequest, CreateResponse, ListFilter]): A configured Party instance with service functions and validators.
### Example Usage
```go
app.PartyConfigure("/api", errors.NewParty[CreateRequest, CreateResponse, ListFilter]().
Create(service.Create).
Update(service.Update).
Delete(service.DeleteWithFeedback).
List(service.ListPaginated).
Get(service.GetByID).
Validation(validateCreateRequest))
```
## Party Methods
### Create
Configures the handler for the `POST /` endpoint.
- **Method**: `Create(fn func(stdContext.Context, T) (R, error))`
- **Description**: Sets the function to be called for creating a resource.
### Update
Configures the handler for the `PUT /{id:string}` endpoint.
- **Method**: `Update(fn func(stdContext.Context, T) (bool, error))`
- **Description**: Sets the function to be called for updating a resource.
### Delete
Configures the handler for the `DELETE /{id:string}` endpoint.
- **Method**: `Delete(fn func(stdContext.Context, string) (bool, error))`
- **Description**: Sets the function to be called for deleting a resource.
### List
Configures the handler for the `POST /list` endpoint.
- **Method**: `List(fn func(stdContext.Context, pagination.ListOptions, F) ([]R, int, error))`
- **Description**: Sets the function to be called for listing resources with pagination and filtering.
### Get
Configures the handler for the `GET /{id:string}` endpoint.
- **Method**: `Get(fn func(stdContext.Context, string) (R, error))`
- **Description**: Sets the function to be called for retrieving a single resource by ID.
### Validation
Sets request validators for the Create and Update operations.
- **Method**: `Validation(validators ...ContextRequestFunc[T]) *Party[T, R, F]`
- **Description**: Appends request validators for the Create and Update endpoints.
### FilterValidation
Sets request validators for the List operation.
- **Method**: `FilterValidation(filterValidators ...ContextRequestFunc[F]) *Party[T, R, F]`
- **Description**: Appends request validators for the List endpoint's filter parameters.
### Intercept
Sets response interceptors for the Create and Update operations.
- **Method**: `Intercept(intercepters ...ContextResponseFunc[T, R]) *Party[T, R, F]`
- **Description**: Appends response interceptors for the Create and Update endpoints.
### FilterIntercept
Sets response interceptors for the List operation.
- **Method**: `FilterIntercept(filterIntercepters ...ContextResponseFunc[F, R]) *Party[T, R, F]`
- **Description**: Appends response interceptors for the List endpoint.
```
--------------------------------
### Install go-playground/validator
Source: https://github.com/kataras/iris/wiki/Model-validation
Use `go get` to install the latest version of the validator library.
```shell
$ go get github.com/go-playground/validator/v10@latest
```
--------------------------------
### Basic Iris Web Server Setup
Source: https://github.com/kataras/iris/blob/main/README.md
Sets up a new Iris application, adds a compression middleware, defines a root route that responds with HTML, and starts the server on port 8080. Ensure Iris is imported.
```go
package main
import "github.com/kataras/iris/v12"
func main() {
app := iris.New()
app.Use(iris.Compression)
app.Get("/", func(ctx iris.Context) {
ctx.HTML("Happy New Year %s! ЁЯОЕ", "World")
})
app.Listen(":8080")
}
```
--------------------------------
### File Server Embedding Files (Bindata) Example
Source: https://github.com/kataras/iris/blob/main/_examples/README.md
This example specifically focuses on the `go-bindata` approach for embedding files. It requires the `go-bindata` tool to be installed and run to generate the asset file.
```go
package main
import (
"github.com/kataras/iris/v12"
// Import the generated bindata package
_ "github.com/kataras/iris/v12/_examples/bindata"
)
// This example assumes you have run:
// go get github.com/go-bindata/go-bindata/...
// go-bindata -pkg main -o assets.go static/"
func main() {
app := iris.New()
// Register the file server middleware with embedded assets
app.HandleDir("/static", iris.Dir("./static").FileSystem(iris.AssetFS))
app.Get("/", func(ctx iris.Context) {
ctx.HTML("
Embedded Files (Bindata)
")
})
app.Listen(":8080")
}
```
--------------------------------
### Install and Run Benchmarks
Source: https://github.com/kataras/iris/blob/main/_benchmarks/view/README.md
Installs the server benchmarks and Bombardier tool, then runs the benchmarks and outputs results to a file.
```sh
$ go install github.com/kataras/server-benchmarks@master
$ go install github.com/codesenberg/bombardier@master
$ server-benchmarks --wait-run=3s -o ./results
```
--------------------------------
### Configure API Guide in Go
Source: https://github.com/kataras/iris/blob/main/README.md
Initializes and configures an API guide for an Iris web application. This setup includes options for CORS, compression, health checks, timeouts, and middleware. The API is exposed at the '/users' path.
```go
package main
import (
// [other packages...]
"github.com/kataras/iris/v12"
)
func main() {
iris.NewGuide().
AllowOrigin("*").
Compression(true).
Health(true, "development", "kataras").
Timeout(0, 20*time.Second, 20*time.Second).
Middlewares(basicauth.New(...)).
Services(
// NewDatabase(),
// NewPostgresRepositoryRegistry,
// NewUserService,
).
API("/users", new(UsersAPI)).
Listen(":80")
}
```
--------------------------------
### Initialize Go Project and Get Iris
Source: https://github.com/kataras/iris/wiki/mvc/mvc-quickstart
Commands to initialize a new Go project and install the Iris framework. Use '@latest' for the most recent stable release.
```bash
go init app
go get -u github.com/kataras/iris/v12@master
```
--------------------------------
### Basic Iris App with Middleware
Source: https://github.com/kataras/iris/wiki/Quick-start
This snippet shows how to create a default Iris application, register middleware, define a GET route, and start the server. It's a foundational example for any Iris project.
```go
package main
import "github.com/kataras/iris/v12"
func main() {
app := iris.Default()
app.Use(myMiddleware)
app.Handle("GET", "/ping", func(ctx iris.Context) {
ctx.JSON(iris.Map{"message": "pong"})
})
// Listens and serves incoming http requests
// on http://localhost:8080.
app.Listen(":8080")
}
func myMiddleware(ctx iris.Context) {
ctx.Application().Logger().Infof("Runs before %s", ctx.Path())
ctx.Next()
}
```
--------------------------------
### Iris Routing: Basic Example
Source: https://github.com/kataras/iris/blob/main/_examples/README.md
A simple demonstration of defining basic GET and POST routes in Iris.
```go
package main
import "github.com/kataras/iris/v12"
func main() {
app := iris.New()
app.Get("/", func(ctx iris.Context) {
ctx.WriteString("Hello from GET request!")
})
app.Post("/", func(ctx iris.Context) {
ctx.WriteString("Hello from POST request!")
})
app.Listen(":3000")
}
```
--------------------------------
### Example: Serve JSON, XML, or HTML based on Accept Header
Source: https://github.com/kataras/iris/wiki/responses/response-content-negotiation
This comprehensive example demonstrates how to set up content negotiation for JSON, XML, and HTML, and then use `ctx.Negotiate` with an `iris.N` struct to provide the data for each format.
```go
type testdata struct {
ID uint64 `json:"id" xml:"ID"`
Name string `json:"name" xml:"Name"`
Age int `json:"age" xml:"Age"`
}
func main() {
users := app.Party("/users")
users.Use(setAcceptTypes)
users.Post("/{id:uint64}", handler)
// [...]
}
func setAcceptTypes(ctx iris.Context) {
ctx.Negotiation().JSON().XML().HTML().EncodingGzip()
ctx.Next()
}
func handler(ctx iris.Context) {
data := testdata{
ID: ctx.Params().GetUint64Default("id", 0),
Name: "Test Name",
Age: 26,
}
ctx.Negotiate(iris.N{
JSON: data,
XML: data,
HTML: "Test Name
Age 26
",
})
}
```
--------------------------------
### Configure and Run MVC Application
Source: https://github.com/kataras/iris/wiki/MVC
Set up a new Iris application and configure an MVC application on a specific party. This example demonstrates basic setup and listening for requests.
```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))
}
```
--------------------------------
### Go: Start WebSocket Server
Source: https://github.com/kataras/iris/blob/main/_examples/websocket/basic/README.md
Executes the Go program to start the WebSocket server.
```sh
go run server.go
```
--------------------------------
### Install protoc-gen-go Tool
Source: https://github.com/kataras/iris/blob/main/_examples/response-writer/protobuf/README.md
Install the Protocol Buffers Go compiler plugin. Ensure you are using the latest version.
```sh
go get -u google.golang.org/protobuf/cmd/protoc-gen-go@latest
```
--------------------------------
### Basic Iris MVC Application Setup
Source: https://github.com/kataras/iris/wiki/MVC
Sets up a new Iris application, adds recovery and logger middleware, and registers an MVC controller for the root path. This is a standard starting point for Iris MVC applications.
```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")
}
```
--------------------------------
### Embedding Templates Into App Executable File (Bindata) Example
Source: https://github.com/kataras/iris/blob/main/_examples/README.md
This example specifically shows the setup for embedding templates using `go-bindata`. It requires running a `go-bindata` command to generate the Go source file containing the embedded assets.
```go
package main
import (
"github.com/kataras/iris/v12"
// Import the generated bindata package
_ "github.com/kataras/iris/v12/_examples/bindata"
)
// This example assumes you have run:
// go get github.com/go-bindata/go-bindata/...
// go-bindata -pkg main -o assets.go views/"
func main() {
app := iris.New()
// Register the view engine with embedded templates
app.RegisterView(iris.HTML("./views", ".html").ParseFunc(func(filename string) ([]byte, error) {
// Use the Asset function from the generated bindata package
return Asset(filename)
}))
app.Get("/", func(ctx iris.Context) {
ctx.View("index.html")
})
app.Listen(":8080")
}
```
--------------------------------
### Client Output Example
Source: https://github.com/kataras/iris/blob/main/_examples/auth/jwt/tutorial/go-client/README.md
Example output from the Go client demonstrating an access token and a created todo item. The access token is a JWT, and the todo item shows the structure of a created resource.
```text
2020/11/04 21:08:40 Access Token:
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiYTAwYzI3ZDEtYjVhYS00NjU0LWFmMTYtYjExNzNkZTY1NjI5Iiwicm9sZXMiOlsiYWRtaW4iXSwiaWF0IjoxNjA0NTE2OTIwLCJleHAiOjE2MDQ1MTc4MjAsImp0aSI6IjYzNmVmMDc0LTE2MzktNGJhZi1hNGNiLTQ4ZDM4NGMxMzliYSIsImlzcyI6Im15YXBwIn0.T9B0zG0AHShO5JfQgrMQBlToH33KHgp8nLMPFpN6QmM"
2020/11/04 21:08:40 Todo Created:
model.Todo{ID:"cfa38d7a-c556-4301-ae1f-fb90f705071c", UserID:"a00c27d1-b5aa-4654-af16-b1173de65629", Title:"test todo title", Body:"test todo body contents", CreatedAt:1604516920}
```
--------------------------------
### VisitController with Session and StartTime
Source: https://github.com/kataras/iris/wiki/mvc/mvc-sessions
Defines a controller that automatically binds the session and receives the server's start time as a dependency. The `Get` method increments a session counter and displays visit information.
```go
type VisitController struct {
Session *sessions.Session
StartTime time.Time
}
func (c *VisitController) Get() string {
// it increments a "visits" value of integer by one,
// if the entry with key 'visits' doesn't exist
// it will create it for you.
visits := c.Session.Increment("visits", 1)
// write the current, updated visits.
since := time.Now().Sub(c.StartTime).Seconds()
return fmt.Sprintf("%d visit(s) from my current session in %0.1f seconds of server's up-time",
visits,
since)
}
```
--------------------------------
### Install Protobuf Compiler Plugin
Source: https://github.com/kataras/iris/wiki/responses/response-protobuf
Installs the protoc-gen-go tool, which is necessary for generating Go code from .proto files.
```sh
$ go get -u google.golang.org/protobuf/cmd/protoc-gen-go@latest
```
--------------------------------
### Install with Docker Compose
Source: https://github.com/kataras/iris/blob/main/_examples/auth/basicauth/database/README.md
Use this command to build and run the application with Docker Compose. Ensure Docker is installed.
```sh
docker-compose up --build
```
--------------------------------
### Install Protoc Go Plugin
Source: https://github.com/kataras/iris/wiki/Grpc
Installs the protoc Go plugin, which is required for generating Go code from .proto files.
```sh
$ go get -u github.com/golang/protobuf/protoc-gen-go
```
--------------------------------
### Install go-bindata
Source: https://github.com/kataras/iris/wiki/file-server/file-server-introduction
Install the go-bindata tool, which is used to convert files into a go file that can be embedded into your application.
```bash
$ go get -u github.com/go-bindata/go-bindata/v3/go-bindata
```
--------------------------------
### Install gqlgen
Source: https://github.com/kataras/iris/blob/main/_examples/graphql/schema-first/README.md
Install the gqlgen tool globally to manage your GraphQL schema and generate Go code.
```sh
$ go install github.com/99designs/gqlgen@latest
```
--------------------------------
### Start Iris Web Server
Source: https://github.com/kataras/iris/blob/main/_examples/mvc/vuejs-todo-mvc/README.md
Starts the Iris web server. Ensure you run this command from the correct directory.
```go
id := sess.Start(ctx).ID()
return id
}
odosWebsocketApp.Router.Get("/", websocket.Handler(websocketServer, idGenerator))
// start the web server at http://localhost:8080
app.Listen(":8080")
}
```
--------------------------------
### Start a Session
Source: https://github.com/kataras/iris/wiki/Sessions
Initiate a user session for the current context. The `Start` method returns a `Session` pointer, which is used to interact with session data. Optional `iris.CookieOption` can be passed to customize cookie behavior.
```go
session := sess.Start(ctx)
```
--------------------------------
### Basic HTML View Example
Source: https://github.com/kataras/iris/blob/main/_examples/README.md
Demonstrates the basic usage of Iris's view engine to render HTML templates. This example uses the default HTML engine.
```go
package main
import (
"github.com/kataras/iris/v12"
)
func main() {
app := iris.New()
// Configure the view engine
app.RegisterView(iris.HTML("./views", ".html"))
// Route to render a template
app.Get("/", func(ctx iris.Context) {
// Render the "index.html" template from the "views" directory
ctx.View("index.html")
})
// Start the server
app.Listen(":8080")
}
```
--------------------------------
### Basic File Server Example
Source: https://github.com/kataras/iris/blob/main/_examples/README.md
Demonstrates how to serve static files from a directory. Ensure the 'static' directory exists.
```go
package main
import (
"github.com/kataras/iris/v12"
)
func main() {
app := iris.New()
// Serve static files from the "static" directory
app.HandleDir("/static", "./static")
// Example route
app.Get("/", func(ctx iris.Context) {
ctx.HTML("Hello, World!
Check out the /static directory.
")
})
// Start the server
app.Listen(":8080")
}
```
--------------------------------
### Install JWT Middleware
Source: https://github.com/kataras/iris/wiki/Request-authentication
Install the JWT middleware using the go get command.
```sh
$ go get github.com/iris-contrib/middleware/jwt
```
--------------------------------
### AccessLog Listen and Render Logs Example
Source: https://github.com/kataras/iris/blob/main/_examples/README.md
Demonstrates how to listen for access log events and render them to a client in real-time. This can be used for live monitoring dashboards.
```go
package main
import (
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/ рокродро┐рокрпНрокрпБ/middleware/accesslog"
)
func main() {
app := iris.New()
// Create a new access log middleware instance
logMiddleware := accesslog.New()
// Register a handler to listen for log events
logMiddleware.Add(func(log accesslog.Log) {
// Here you can process the log entry, e.g., send it over a websocket
// For this example, we'll just print it to the console
iris.GetFromContext(log.Context).Application().Logger().Infof("Access Log: %+v\n", log)
})
// Use the access log middleware
app.Use(logMiddleware)
// Example route
app.Get("/", func(ctx iris.Context) {
ctx.WriteString("Hello, Live Access Log!")
})
// Start the server
app.Listen(":8080")
}
```
--------------------------------
### Go Session Management Example
Source: https://github.com/kataras/iris/wiki/Sessions
Demonstrates how to set up and use sessions for authentication. Users must log in to access a secret page and can log out to revoke access. Includes routes for secret, login, and logout.
```go
package main
import (
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/sessions"
)
var (
cookieNameForSessionID = "mycookiesessionnameid"
sess = sessions.New(sessions.Config{Cookie: cookieNameForSessionID})
)
func secret(ctx iris.Context) {
// Check if user is authenticated
if auth, _ := sess.Start(ctx).GetBoolean("authenticated"); !auth {
ctx.StatusCode(iris.StatusForbidden)
return
}
// Print secret message
ctx.WriteString("The cake is a lie!")
}
func login(ctx iris.Context) {
session := sess.Start(ctx)
// Authentication goes here
// ...
// Set user as authenticated
session.Set("authenticated", true)
}
func logout(ctx iris.Context) {
session := sess.Start(ctx)
// Revoke users authentication
session.Set("authenticated", false)
// Or to remove the variable:
session.Delete("authenticated")
// Or destroy the whole session:
session.Destroy()
}
func main() {
app := iris.New()
app.Get("/secret", secret)
app.Get("/login", login)
app.Get("/logout", logout)
app.Listen(":8080")
}
```
--------------------------------
### Main Application Setup (Go)
Source: https://github.com/kataras/iris/blob/main/_examples/mvc/vuejs-todo-mvc/README.md
Configures the Iris application, sets up static file serving for the Vue.js frontend, initializes sessions, and registers MVC and WebSocket controllers.
```go
// file: web/main.go
package main
import (
"strings"
"github.com/kataras/iris/v12/_examples/mvc/vuejs-todo-mvc/src/todo"
"github.com/kataras/iris/v12/_examples/mvc/vuejs-todo-mvc/src/web/controllers"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/mvc"
"github.com/kataras/iris/v12/sessions"
"github.com/kataras/iris/v12/websocket"
)
func main() {
app := iris.New()
// serve our app in public, public folder
// contains the client-side vue.js application,
// no need for any server-side template here,
// actually if you're going to just use vue without any
// back-end services, you can just stop afer this line and start the server.
app.HandleDir("/", iris.Dir("./public"))
// configure the http sessions.
sess := sessions.New(sessions.Config{
Cookie: "iris_session",
})
// create a sub router and register the http controllers.
odosRouter := app.Party("/todos")
// create our mvc application targeted to /todos relative sub path.
odosApp := mvc.New(todosRouter)
// any dependencies bindings here...
odosApp.Register(
todo.NewMemoryService(),
)
odosController := new(controllers.TodoController)
// controllers registration here...
odosApp.Handle(todosController)
// Create a sub mvc app for websocket controller.
// Inherit the parent's dependencies.
odosWebsocketApp := todosApp.Party("/sync")
odosWebsocketApp.HandleWebsocket(todosController).
SetNamespace("todos").
SetEventMatcher(func(methodName string) (string, bool) {
return strings.ToLower(methodName), true
})
websocketServer := websocket.New(websocket.DefaultGorillaUpgrader, todosWebsocketApp)
idGenerator := func(ctx iris.Context) string {
```
--------------------------------
### ExampleController with Standard HTTP Methods
Source: https://github.com/kataras/iris/wiki/mvc/mvc-mvc
Defines an ExampleController that handles GET requests for the root path, '/ping', and '/hello'. It demonstrates returning HTML, a string, and a JSON map.
```go
// ExampleController serves the "/", "/ping" and "/hello".
type ExampleController struct{}
```
```go
// Get serves
// Method: GET
// Resource: http://localhost:8080
func (c *ExampleController) Get() mvc.Result {
return mvc.Response{
ContentType: "text/html",
Text: "Welcome
",
}
}
```
```go
// GetPing serves
// Method: GET
// Resource: http://localhost:8080/ping
func (c *ExampleController) GetPing() string {
return "pong"
}
```
```go
// GetHello serves
// Method: GET
// Resource: http://localhost:8080/hello
func (c *ExampleController) GetHello() interface{} {
return map[string]string{"message": "Hello Iris!"}
}
```
--------------------------------
### Accessing URL Parameters in an Iris Route
Source: https://github.com/kataras/iris/wiki/URL-query-parameters
This example demonstrates how to retrieve URL query parameters within an Iris route handler. It shows the usage of `URLParamDefault` to get a parameter with a fallback value and `URLParam` to get a parameter directly.
```go
app.Get("/welcome", func( ctx iris.Context) {
firstname := ctx.URLParamDefault("firstname", "Guest")
lastname := ctx.URLParam("lastname")
ctx.Writef("Hello %s %s", firstname, lastname)
})
```
--------------------------------
### Iris Routing: Overview
Source: https://github.com/kataras/iris/blob/main/_examples/README.md
Provides a basic example of setting up routes and handlers in Iris.
```go
package main
import "github.com/kataras/iris/v12"
func main() {
app := iris.New()
app.Get("/", func(ctx iris.Context) {
ctx.HTML("Hello World!
")
})
app.Post("/submit", func(ctx iris.Context) {
ctx.JSON(iris.Map{"message": "Data received"})
})
app.Listen(":3000")
}
```
--------------------------------
### Install Iris on an Existing Project
Source: https://github.com/kataras/iris/blob/main/README.md
Navigate to your existing project directory and run this command to get the latest Iris version.
```sh
cd myapp
go get github.com/kataras/iris/v12@latest
```
--------------------------------
### Configure Negotiation Builder and Negotiate
Source: https://github.com/kataras/iris/wiki/responses/response-content-negotiation
This example shows how to configure the negotiation builder with specific data for JSON, XML, and HTML, and then call `ctx.Negotiate(nil)` to use the builder's content.
```go
func handler(ctx iris.Context) {
// data := [...]
ctx.Negotiation().
JSON(data).
XML(data).
HTML("Test Name
Age 26
").
EncodingGzip().
Charset("utf-8")
err := ctx.Negotiate(nil)
// [handle err]
}
```
--------------------------------
### Go: Iris App Setup and Routes
Source: https://github.com/kataras/iris/blob/main/_examples/dropzonejs/README_PART2.md
Sets up an Iris application, registers HTML views, serves static files from './public', and defines routes for the homepage and retrieving uploaded files.
```go
func main() {
app := iris.New()
app.RegisterView(iris.HTML("./views", ".html"))
app.HandleDir("/public", iris.Dir("./public"))
app.Get("/", func(ctx iris.Context) {
if err := ctx.View("upload.html"); err != nil {
ctx.HTML(fmt.Sprintf("%s
", err.Error()))
return
}
})
files := scanUploads(uploadsDir)
app.Get("/uploads", func(ctx iris.Context) {
ctx.JSON(files.items)
})
app.Post("/upload", iris.LimitRequestBodySize(10<<20), func(ctx iris.Context) {
// Get the file from the dropzone request
file, info, err := ctx.FormFile("file")
if err != nil {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.Application().Logger().Warnf("Error while uploading: %v", err.Error())
return
}
defer file.Close()
fname := info.Filename
// Create a file with the same name
// assuming that you have a folder named 'uploads'
out, err := os.OpenFile(uploadsDir+fname,
os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.Application().Logger().Warnf("Error while preparing the new file: %v", err.Error())
return
}
defer out.Close()
io.Copy(out, file)
// optionally, add that file to the list in order to be visible when refresh.
uploadedFile := files.add(fname, info.Size)
go files.createThumbnail(uploadedFile)
})
// start the server at http://localhost:8080
}
```
--------------------------------
### Get uint64 Path Parameter
Source: https://github.com/kataras/iris/wiki/Routing-path-parameter-types
Example of retrieving a uint64 path parameter from the context. The `GetUint64Default` method provides a default value if the parameter is not found or cannot be converted.
```go
app.Get("/users/{id:uint64}", func(ctx iris.Context){
id := ctx.Params().GetUint64Default("id", 0)
// [...]
})
```
--------------------------------
### Record Operation Log in Global Interceptor
Source: https://github.com/kataras/iris/wiki/Response-recorder
This example demonstrates how to use `ctx.Record()` in a middleware to start recording the response, and then access the recorded body in a `Done` middleware for logging.
```go
package main
import "github.com/kataras/iris/v12"
func main() {
app := iris.New()
// start record.
app.Use(func(ctx iris.Context) {
ctx.Record()
ctx.Next()
})
// collect and "log".
app.Done(func(ctx iris.Context) {
body := ctx.Recorder().Body()
// Should print success.
app.Logger().Infof("sent: %s", string(body))
})
}
```
--------------------------------
### Initialize Project and Get Iris
Source: https://github.com/kataras/iris/blob/main/_examples/mvc/overview/README.md
Commands to initialize a new Go project and fetch the Iris framework. Use '@main' for the latest development version or '@latest' for the most recent official release.
```sh
go init app
go get github.com/kataras/iris/v12@main
```
--------------------------------
### Iris App with HTML Templates and Dynamic Routes
Source: https://github.com/kataras/iris/wiki/Quick-start
This example demonstrates setting up Iris to render HTML templates from a specified directory and handling routes with dynamic URL parameters like user IDs. It requires an './views' folder with an 'hello.html' file.
```go
package main
import "github.com/kataras/iris/v12"
func main() {
app := iris.New()
// Load all templates from the "./views" folder
// where extension is ".html" and parse them
// using the standard `html/template` package.
app.RegisterView(iris.HTML("./views", ".html"))
// Method: GET
// Resource: http://localhost:8080
app.Get("/", func(ctx iris.Context) {
// Bind: {{.message}} with "Hello world!"
ctx.ViewData("message", "Hello world!")
// Render template file: ./views/hello.html
ctx.View("hello.html")
})
// Method: GET
// Resource: http://localhost:8080/user/42
//
// Need to use a custom regexp instead?
// Easy;
// Just mark the parameter's type to 'string'
// which accepts anything and make use of
// its `regexp` macro function, i.e:
// app.Get("/user/{id:string regexp(^[0-9]+$)}")
app.Get("/user/{id:uint64}", func(ctx iris.Context) {
userID, _ := ctx.Params().GetUint64("id")
ctx.Writef("User ID: %d", userID)
})
// Start the server using a network address.
app.Listen(":8080")
}
```
--------------------------------
### Vue Router SPA Example
Source: https://github.com/kataras/iris/blob/main/_examples/README.md
Configures Iris to serve a Single Page Application (SPA) built with Vue Router. This setup handles client-side routing by serving the index.html for all non-API routes.
```go
package main
import (
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/fs"
)
func main() {
app := iris.New()
// Serve the SPA from the "frontend/dist" directory
// The "fs.New" creates a new file system middleware.
// The "fs.New().Add("/", "index.html")" ensures that requests to the root
// are served by index.html, which is crucial for SPAs.
spa := fs.New(fs.Config{
FileSystem: iris.Dir("./frontend/dist"),
IndexName: "index.html",
Gzip: true, // Enable Gzip compression
})
// Register the SPA middleware for all routes that don't match API routes
// This is a common pattern for SPAs where the frontend handles routing.
app.SPA(spa)
// Example API route (optional)
app.Get("/api/hello", func(ctx iris.Context) {
ctx.JSON(iris.Map{"message": "Hello from API!"})
})
// Start the server on port 8080
app.Listen(":8080")
}
```
--------------------------------
### Tidy Dependencies and Run Iris Application
Source: https://github.com/kataras/iris/blob/main/README.md
After installing Iris, run 'go mod tidy' to ensure all dependencies are correctly managed, then use 'go run .' to start your application. Note the '-compat' flag for Windows.
```sh
go mod tidy -compat=1.23
go run .
```
--------------------------------
### Running the Iris Middleware Example
Source: https://github.com/kataras/iris/wiki/Routing-middleware
Execute the Go program and access the specified URL to observe the middleware execution flow and output.
```sh
$ go run main.go # and navigate to the http://localhost:8080
Now listening on: http://localhost:8080
Application started. Press CTRL+C to shut down.
Before the mainHandler: /
Inside mainHandler
After the mainHandler
```
--------------------------------
### Start a Session in a Route Handler
Source: https://github.com/kataras/iris/wiki/Sessions-flash-messages
Start a session within an Iris route handler to access session functionalities, including flash messages. Ensure the session is started before attempting to use its methods.
```go
// [app := iris.New...]
app.Get("/path", func(ctx iris.Context) {
session := sess.Start(ctx)
// [...]
```
--------------------------------
### Create and Configure a New Host Manually
Source: https://github.com/kataras/iris/wiki/Host
Manually create a new host using `app.NewHost` and register shutdown callbacks before running the application with `iris.Raw` runner. Requires importing `net/http`.
```go
h := app.NewHost(&http.Server{Addr:":8080"})
h.RegisterOnShutdown(func(){
println("server terminated")
})
app.Run(iris.Raw(h.ListenAndServe))
```
--------------------------------
### Iris Configuration: Using Viper
Source: https://github.com/kataras/iris/blob/main/_examples/README.md
Demonstrates integrating the Viper configuration library with Iris.
```go
package main
import (
"github.com/kataras/iris/v12"
"github.com/spf13/viper"
)
func main() {
viper.Set("port", 3000)
// Other Viper configurations...
app := iris.New()
// Use Viper configuration values
app.Listen(viper.GetString("port"))
app.Listen(":3000")
}
```
--------------------------------
### Browserify: Install NPM Dependencies
Source: https://github.com/kataras/iris/blob/main/_examples/websocket/basic/README.md
Installs the necessary Node.js packages for the Browserify client.
```sh
cd ./browserify
npm install
```
--------------------------------
### Node.js Client: Install NPM Dependencies
Source: https://github.com/kataras/iris/blob/main/_examples/websocket/basic/README.md
Installs the necessary Node.js packages for the Node.js client.
```sh
cd nodejs-client
npm install
```
--------------------------------
### Entity Not Found Error Response Example
Source: https://github.com/kataras/iris/blob/main/_examples/database/mysql/README.md
Example of a JSON response when a requested entity cannot be found.
```json
{
"code": 404,
"message": "entity does not exist",
"timestamp": 1589306199
}
```
--------------------------------
### Basic SSE Client Setup
Source: https://github.com/kataras/iris/blob/main/_examples/response-writer/sse/optional.sse.mini.js.html
Instantiate an EventSource to connect to the server's event stream. Attach an 'onmessage' handler to process incoming data. Open your browser's developer console (F12) to view the logged messages.
```javascript
var client = new EventSource("http://localhost:8080/events")
client.onmessage = function (evt) {
console.log(evt)
}
```
--------------------------------
### Basic Dependency Injection in Go
Source: https://github.com/kataras/iris/blob/main/_examples/README.md
A simple example demonstrating Iris's dependency injection container. It shows how to register and resolve basic types.
```go
package main
import (
"fmt"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/core/di"
)
type MyService struct {
Message string
}
func (s *MyService) Greet() string {
return "Hello, " + s.Message
}
func main() {
app := iris.New()
// Create a new DI container
container := di.New()
// Register a singleton instance of MyService
container.Register(&MyService{Message: "World"})
// Register a factory function for a different type
container.Register(func() string { return "Dynamic String" })
// Use the container to resolve dependencies in a handler
app.Get("/", func(ctx iris.Context) {
var service *MyService
var dynamicString string
// Resolve dependencies from the container
err := ctx.Application().Container().Resolve(&service, &dynamicString)
if err != nil {
ctx.Application().Logger().Errorf("Failed to resolve dependencies: %v", err)
ctx.StatusCode(iris.StatusInternalServerError)
return
}
response := fmt.Sprintf("%s | %s", service.Greet(), dynamicString)
ctx.WriteString(response)
})
app.Listen(":8080")
}
```
--------------------------------
### Match GET "/"
Source: https://github.com/kataras/iris/wiki/Routing
This snippet matches only GET requests to the root path "/".
```go
app.Get("/", indexHandler)
```
--------------------------------
### Build Simple JSON APIs with New Guide
Source: https://github.com/kataras/iris/blob/main/HISTORY.md
Introduces `iris.NewGuide` for building simple JSON APIs with dependency injection and improved design patterns.
```go
package main
import (
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/guides/newguide"
)
type MyService struct {
// Dependencies can be injected here
}
func (s *MyService) GetData() string {
return "Data from MyService"
}
func main() {
app := iris.New()
// Create a new guide instance with the service
guide := newguide.New(app, &MyService{})
// Define a JSON API endpoint
guide.Get("/api/data", func(ctx iris.Context, service *MyService) {
data := service.GetData()
ctx.JSON(iris.Map{
"data": data,
})
})
app.Listen(":8080")
}
```
--------------------------------
### Initialize Iris Server
Source: https://github.com/kataras/iris/blob/main/middleware/jwt/ARTICLE.md
Sets up a basic Iris application and starts a server on port 8080.
```go
package main
import "github.com/kataras/iris/v12"
func main() {
// Create a new Iris application.
app := iris.New()
// Register a simple GET handler at the root path.
app.Get("/", func(ctx iris.Context) {
ctx.WriteString("Hello, world!")
})
// Start the server at http://localhost:8080.
app.Listen(":8080")
}
```
--------------------------------
### Building a Route Path with Parameters
Source: https://github.com/kataras/iris/blob/main/_proposals/route_builder.md
Demonstrates how to use the RouteBuilder to construct a URL path including string, integer, and wildcard parameters with custom functions.
```go
package main
import (
"fmt"
"strings"
"github.com/kataras/iris/v12/macro"
)
func main() {
path := NewRouteBuilder().
Path("/user").
String("name", "prefix(ma)", "suffix(kis)").
Int("age").
Path("/friends").
Wildcard("rest").
Build()
fmt.Println(path)
}
type RouteBuilder struct {
path string
}
func NewRouteBuilder() *RouteBuilder {
return &RouteBuilder{
path: "/",
}
}
func (r *RouteBuilder) Path(path string) *RouteBuilder {
if path[0] != '/' {
path = "/" + path
}
r.path = strings.TrimSuffix(r.path, "/") + path
return r
}
type StaticPathBuilder interface {
Path(path string) *RouteBuilder
}
func (r *RouteBuilder) Param(param ParamBuilder) *RouteBuilder { // StaticPathBuilder {
path := "" // keep it here, a single call to r.Path must be done.
if len(r.path) == 0 || r.path[len(r.path)-1] != '/' {
path += "/" // if for some reason no prior Path("/") was called for delimeter between path parameter.
}
path += fmt.Sprintf("{%s:%s", param.GetName(), param.GetParamType().Indent())
if funcs := param.GetFuncs(); len(funcs) > 0 {
path += fmt.Sprintf(" %s", strings.Join(funcs, " "))
}
path += "}"
return r.Path(path)
}
func (r *RouteBuilder) String(name string, funcs ...string) *RouteBuilder {
return r.Param(Param(macro.String, name, funcs...))
}
func (r *RouteBuilder) Int(name string, funcs ...string) *RouteBuilder {
return r.Param(Param(macro.Int, name, funcs...))
}
func (r *RouteBuilder) Int8(name string, funcs ...string) *RouteBuilder {
return r.Param(Param(macro.Int8, name, funcs...))
}
func (r *RouteBuilder) Int16(name string, funcs ...string) *RouteBuilder {
return r.Param(Param(macro.Int16, name, funcs...))
}
func (r *RouteBuilder) Int32(name string, funcs ...string) *RouteBuilder {
return r.Param(Param(macro.Int32, name, funcs...))
}
func (r *RouteBuilder) Int64(name string, funcs ...string) *RouteBuilder {
return r.Param(Param(macro.Int64, name, funcs...))
}
func (r *RouteBuilder) Uint(name string, funcs ...string) *RouteBuilder {
return r.Param(Param(macro.Uint, name, funcs...))
}
func (r *RouteBuilder) Uint8(name string, funcs ...string) *RouteBuilder {
return r.Param(Param(macro.Uint8, name, funcs...))
}
func (r *RouteBuilder) Uint16(name string, funcs ...string) *RouteBuilder {
return r.Param(Param(macro.Uint16, name, funcs...))
}
func (r *RouteBuilder) Uint32(name string, funcs ...string) *RouteBuilder {
return r.Param(Param(macro.Uint32, name, funcs...))
}
func (r *RouteBuilder) Uint64(name string, funcs ...string) *RouteBuilder {
return r.Param(Param(macro.Uint64, name, funcs...))
}
func (r *RouteBuilder) Bool(name string, funcs ...string) *RouteBuilder {
return r.Param(Param(macro.Bool, name, funcs...))
}
func (r *RouteBuilder) Alphabetical(name string, funcs ...string) *RouteBuilder {
return r.Param(Param(macro.Alphabetical, name, funcs...))
}
func (r *RouteBuilder) File(name string, funcs ...string) *RouteBuilder {
return r.Param(Param(macro.File, name, funcs...))
}
func (r *RouteBuilder) Wildcard(name string, funcs ...string) *RouteBuilder {
return r.Param(Param(macro.Path, name, funcs...))
}
func (r *RouteBuilder) UUID(name string, funcs ...string) *RouteBuilder {
return r.Param(Param(macro.UUID, name, funcs...))
}
func (r *RouteBuilder) Mail(name string, funcs ...string) *RouteBuilder {
return r.Param(Param(macro.Mail, name, funcs...))
}
func (r *RouteBuilder) Email(name string, funcs ...string) *RouteBuilder {
return r.Param(Param(macro.Email, name, funcs...))
}
func (r *RouteBuilder) Date(name string, funcs ...string) *RouteBuilder {
return r.Param(Param(macro.Date, name, funcs...))
}
func (r *RouteBuilder) Weekday(name string, funcs ...string) *RouteBuilder {
return r.Param(Param(macro.Weekday, name, funcs...))
}
func (r *RouteBuilder) Build() string {
return r.path
}
type ParamBuilder interface {
GetName() string
GetFuncs() []string
GetParamType() *macro.Macro
}
type pathParam struct {
Name string
Funcs []string
ParamType *macro.Macro
}
var _ ParamBuilder = (*pathParam)(nil)
func Param(paramType *macro.Macro, name string, funcs ...string) ParamBuilder {
return &pathParam{
Name: name,
ParamType: paramType,
Funcs: funcs,
}
}
func (p *pathParam) GetName() string {
return p.Name
}
func (p *pathParam) GetParamType() *macro.Macro {
return p.ParamType
}
func (p *pathParam) GetFuncs() []string {
return p.Funcs
}
```
--------------------------------
### Validation Error Response Example
Source: https://github.com/kataras/iris/blob/main/_examples/database/mysql/README.md
Example of a JSON response when validation fails, indicating missing required fields.
```json
{
"code": 422,
"message": "required fields are missing",
"timestamp": 1589306271
}
```
--------------------------------
### Install Neffos WebSocket Library
Source: https://github.com/kataras/iris/wiki/Websockets
Install the Neffos library, which is a websocket framework for net/http and Iris. It comes pre-installed with Iris.
```sh
$ go get github.com/kataras/neffos@latest
```
--------------------------------
### Iris Configuration: Functional Options
Source: https://github.com/kataras/iris/blob/main/_examples/README.md
Demonstrates configuring Iris using a functional options pattern.
```go
package main
import "github.com/kataras/iris/v12"
func main() {
app := iris.New(iris.WithOptimizations, iris.WithoutVersionCheck)
app.Get("/", func(ctx iris.Context) {
ctx.JSON(iris.Map{"message": "Hello World"})
})
app.Listen(":3000")
}
```
--------------------------------
### Unknown JSON Field Error Response Example
Source: https://github.com/kataras/iris/blob/main/_examples/database/mysql/README.md
Example of a JSON response when the request body contains an unrecognized field.
```json
{
"code": 400,
"message": "json: unknown field \"field_not_exists\"",
"timestamp": 1589306367
}
```