Getting Started with the Go Iris Web Framework

Installation

Note: Requires Go version 1.20 or higher.

$ mkdir myapp
$ cd myapp
$ go mod init myapp
$ go get github.com/kataras/iris/v12@latest

Import it in your code:

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

Troubleshooting Installation

If you encounter network errors during the installation, ensure that the GOPROXY environment variable is set to a valid value.

go env -w GOPROXY=https://goproxy.io,direct

If the above methods do not resolve the issue, clear the go module cache:

go clean --modcache

Quick Start

Functional Mode

$ cat main.go
package main

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

func main() {
    // Define the iris instance
    app := iris.New()

    // Define a route group, (here defines a route group with a /books prefix)
    booksAPI := app.Party("/books")
    {
        // Use middleware
        booksAPI.Use(iris.Compression)

        // Set routes and route handlers
        // GET: http://localhost:8080/books
        booksAPI.Get("/", list)
        // POST: http://localhost:8080/books
        booksAPI.Post("/", create)
    }

    // Listen on port
    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)
    // Note: Response negotiation based on server's priority and client's preference
    // instead of using ctx.JSON:
    // ctx.Negotiation().JSON().MsgPack().Protobuf()
    // ctx.Negotiate(books)
}

func create(ctx iris.Context) {
    var b Book
    err := ctx.ReadJSON(&b)
    // Note: use ctx.ReadBody(&b) to bind incoming data of any type.
    if err != nil {
        ctx.StopWithProblem(iris.StatusBadRequest, iris.NewProblem().
            Title("Failed to create book").DetailErr(err))
        // Note: Use ctx.StopWithError(code, err) when expecting a plain text response only in case of error.
        return
    }

    println("Received book: " + b.Title)

    ctx.StatusCode(iris.StatusCreated)
}

MVC Architectural Pattern

Import the MVC package

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

Set up the controller based on the route group

m := mvc.New(booksAPI)
m.Handle(new(BookController))

Controller implementation

type BookController struct {
    /* Dependency Injection */
}

// Respond to GET: http://localhost:8080/books
func (c *BookController) Get() []Book {
    return []Book{
        {"Mastering Go Concurrency"},
        {"Go Design Patterns"},
        {"Black Hat Go"},
    }
}

// Respond to POST: http://localhost:8080/books
func (c *BookController) Post(b Book) int {
    println("Received book: " + b.Title)

    return iris.StatusCreated
}

Run your Iris Web server:

$ go run main.go
> Listening on: http://localhost:8080
> Application has started. Press CTRL+C to shut down.

List books:

$ curl --header 'Accept-Encoding:gzip' http://localhost:8080/books

[
  {
    "title": "Mastering Go Concurrency"
  },
  {
    "title": "Go Design Patterns"
  },
  {
    "title": "Black Hat Go"
  }
]

Create a new book:

$ 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

This is an example of an error response:

$ curl -X POST --data "{\"title\" \"Invalid Book\"}" \
http://localhost:8080/books

> HTTP/1.1 400 Bad Request

{
  "status": 400,
  "title": "Book creation failed",
  "detail": "invalid character '\"' after object key"
}