1. import "github.com/kataras/iris/v12"
    2. func main() {
    3. app := iris.New()
    4. booksAPI := app.Party("/books")
    5. {
    6. booksAPI.Use(iris.Compression)
    7. // GET: http://localhost:8080/books
    8. booksAPI.Get("/", list)
    9. // POST: http://localhost:8080/books
    10. booksAPI.Post("/", create)
    11. }
    12. app.Listen(":8080")
    13. }
    14. // Book example.
    15. type Book struct {
    16. Title string `json:"title"`
    17. }
    18. func list(ctx iris.Context) {
    19. books := []Book{
    20. {"Mastering Concurrency in Go"},
    21. {"Go Design Patterns"},
    22. {"Black Hat Go"},
    23. }
    24. // TIP: negotiate the response between server's prioritizes
    25. // and client's requirements, instead of ctx.JSON:
    26. // ctx.Negotiation().JSON().MsgPack().Protobuf()
    27. // ctx.Negotiate(books)
    28. }
    29. func create(ctx iris.Context) {
    30. var b Book
    31. err := ctx.ReadJSON(&b)
    32. // TIP: use ctx.ReadBody(&b) to bind
    33. // any type of incoming data instead.
    34. if err != nil {
    35. ctx.StopWithProblem(iris.StatusBadRequest, iris.NewProblem().
    36. Title("Book creation failure").DetailErr(err))
    37. // TIP: use ctx.StopWithError(code, err) when only
    38. // plain text responses are expected on errors.
    39. return
    40. }
    41. println("Received Book: " + b.Title)
    42. ctx.StatusCode(iris.StatusCreated)
    43. }
    1. import "github.com/kataras/iris/v12/mvc"
    1. type BookController struct {
    2. /* dependencies */
    3. }
    4. // GET: http://localhost:8080/books
    5. func (c *BookController) Get() []Book {
    6. {"Go Design Patterns"},
    7. {"Black Hat Go"},
    8. }
    9. }
    10. // POST: http://localhost:8080/books
    11. func (c *BookController) Post(b Book) int {
    12. println("Received Book: " + b.Title)
    13. return iris.StatusCreated
    14. }

    Run your Iris web server:

    1. $ go run main.go
    2. > Now listening on: http://localhost:8080
    3. > Application started. Press CTRL+C to shut down.

    Create a new Book:

    1. $ curl -i -X POST \
    2. --header 'Content-Encoding:gzip' \
    3. --header 'Content-Type:application/json' \
    4. --data "{\"title\":\"Writing An Interpreter In Go\"}" \
    5. http://localhost:8080/books
    6. > HTTP/1.1 201 Created
    1. $ curl -X POST --data "{\"title\" \"not valid one\"}" \
    2. http://localhost:8080/books
    3. > HTTP/1.1 400 Bad Request
    4. {
    5. "status": 400,
    6. "title": "Book creation failure"
    7. "detail": "invalid character '\"' after object key",